summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md37
-rw-r--r--Godeps/Godeps.json21
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/Makefile15
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/affine.go174
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur.go68
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur_test.go207
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/Makefile11
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve.go274
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve_test.go78
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/Makefile15
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect.go133
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect_test.go77
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/doc.go31
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral.go93
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral_test.go156
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser.go125
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser_test.go75
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector.go55
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector_test.go49
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/Makefile11
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/graphicstest.go112
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/Makefile13
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear.go206
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear_test.go143
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/doc.go25
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/interp.go29
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate.go35
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate_test.go169
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale.go31
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale_test.go153
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/shared_test.go69
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail.go41
-rw-r--r--Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail_test.go53
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/LICENSE21
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/README.md160
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/adjust.go200
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/effects.go187
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go392
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/resize.go564
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/tools.go182
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/transform.go201
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/utils.go77
-rw-r--r--Godeps/_workspace/src/github.com/mssola/user_agent/.travis.yml1
-rw-r--r--Godeps/_workspace/src/github.com/mssola/user_agent/all_test.go8
-rw-r--r--Godeps/_workspace/src/github.com/mssola/user_agent/browser.go18
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/.travis.yml7
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/LICENSE13
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/README.md149
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/converter.go452
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/converter_test.go43
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/filters.go143
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/nearest.go318
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/nearest_test.go57
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/resize.go614
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/resize_test.go314
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/thumbnail.go55
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/thumbnail_test.go47
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/ycc.go227
-rw-r--r--Godeps/_workspace/src/github.com/nfnt/resize/ycc_test.go214
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/buffer.go69
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/compress.go58
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/consts.go133
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/lzw/reader.go277
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/reader.go681
-rw-r--r--Godeps/_workspace/src/golang.org/x/image/tiff/writer.go438
-rw-r--r--NOTICE.txt73
-rw-r--r--api/admin.go31
-rw-r--r--api/admin_test.go32
-rw-r--r--api/api.go1
-rw-r--r--api/api_test.go3
-rw-r--r--api/channel.go6
-rw-r--r--api/channel_test.go2
-rw-r--r--api/command.go4
-rw-r--r--api/context.go53
-rw-r--r--api/export.go8
-rw-r--r--api/file.go155
-rw-r--r--api/file_benchmark_test.go2
-rw-r--r--api/file_test.go56
-rw-r--r--api/import.go4
-rw-r--r--api/post.go72
-rw-r--r--api/post_test.go92
-rw-r--r--api/server.go6
-rw-r--r--api/team.go147
-rw-r--r--api/team_test.go111
-rw-r--r--api/templates/error.html2
-rw-r--r--api/templates/signup_team_body.html3
-rw-r--r--api/templates/welcome_body.html12
-rw-r--r--api/templates/welcome_subject.html2
-rw-r--r--api/user.go173
-rw-r--r--api/user_test.go52
-rw-r--r--api/web_socket_test.go11
-rw-r--r--api/webhook.go119
-rw-r--r--api/webhook_test.go162
-rw-r--r--config/config.json114
-rw-r--r--doc/README.md4
-rw-r--r--doc/developer/code-contribution.md19
-rw-r--r--doc/help/enduser/markdown.md152
-rw-r--r--doc/install/single-container-install.md8
-rw-r--r--docker/dev/config_docker.json119
-rw-r--r--docker/local/config_docker.json119
-rw-r--r--manualtesting/manual_testing.go2
-rw-r--r--mattermost.go6
-rw-r--r--model/channel.go8
-rw-r--r--model/client.go78
-rw-r--r--model/config.go135
-rw-r--r--model/team.go21
-rw-r--r--model/user.go6
-rw-r--r--model/webhook.go101
-rw-r--r--model/webhook_test.go82
-rw-r--r--store/sql_session_store.go18
-rw-r--r--store/sql_session_store_test.go23
-rw-r--r--store/sql_store.go50
-rw-r--r--store/sql_team_store.go5
-rw-r--r--store/sql_user_store.go21
-rw-r--r--store/sql_user_store_test.go20
-rw-r--r--store/sql_webhook_store.go128
-rw-r--r--store/sql_webhook_store_test.go77
-rw-r--r--store/store.go12
-rw-r--r--utils/config.go68
-rw-r--r--utils/mail.go56
-rw-r--r--web/react/components/activity_log_modal.jsx7
-rw-r--r--web/react/components/admin_console/admin_controller.jsx105
-rw-r--r--web/react/components/admin_console/admin_sidebar.jsx222
-rw-r--r--web/react/components/admin_console/email_settings.jsx617
-rw-r--r--web/react/components/admin_console/gitlab_settings.jsx277
-rw-r--r--web/react/components/admin_console/image_settings.jsx496
-rw-r--r--web/react/components/admin_console/log_settings.jsx74
-rw-r--r--web/react/components/admin_console/privacy_settings.jsx163
-rw-r--r--web/react/components/admin_console/rate_settings.jsx272
-rw-r--r--web/react/components/admin_console/reset_password_modal.jsx132
-rw-r--r--web/react/components/admin_console/select_team_modal.jsx193
-rw-r--r--web/react/components/admin_console/service_settings.jsx296
-rw-r--r--web/react/components/admin_console/sql_settings.jsx283
-rw-r--r--web/react/components/admin_console/team_settings.jsx235
-rw-r--r--web/react/components/admin_console/team_users.jsx178
-rw-r--r--web/react/components/admin_console/user_item.jsx266
-rw-r--r--web/react/components/channel_header.jsx2
-rw-r--r--web/react/components/channel_loader.jsx44
-rw-r--r--web/react/components/channel_notifications.jsx16
-rw-r--r--web/react/components/create_comment.jsx13
-rw-r--r--web/react/components/create_post.jsx103
-rw-r--r--web/react/components/delete_channel_modal.jsx3
-rw-r--r--web/react/components/email_verify.jsx14
-rw-r--r--web/react/components/error_bar.jsx85
-rw-r--r--web/react/components/file_attachment.jsx10
-rw-r--r--web/react/components/file_attachment_list.jsx16
-rw-r--r--web/react/components/file_upload.jsx3
-rw-r--r--web/react/components/invite_member_modal.jsx2
-rw-r--r--web/react/components/login.jsx13
-rw-r--r--web/react/components/more_direct_channels.jsx2
-rw-r--r--web/react/components/navbar.jsx2
-rw-r--r--web/react/components/new_channel_modal.jsx3
-rw-r--r--web/react/components/password_reset_send_link.jsx7
-rw-r--r--web/react/components/popover_list_members.jsx2
-rw-r--r--web/react/components/post.jsx51
-rw-r--r--web/react/components/post_body.jsx2
-rw-r--r--web/react/components/post_info.jsx16
-rw-r--r--web/react/components/post_list.jsx22
-rw-r--r--web/react/components/post_list_container.jsx1
-rw-r--r--web/react/components/register_app_modal.jsx2
-rw-r--r--web/react/components/rhs_comment.jsx16
-rw-r--r--web/react/components/rhs_header_post.jsx1
-rw-r--r--web/react/components/rhs_root_post.jsx9
-rw-r--r--web/react/components/search_results_header.jsx1
-rw-r--r--web/react/components/search_results_item.jsx2
-rw-r--r--web/react/components/settings_sidebar.jsx3
-rw-r--r--web/react/components/sidebar.jsx2
-rw-r--r--web/react/components/sidebar_right_menu.jsx4
-rw-r--r--web/react/components/signup_team.jsx56
-rw-r--r--web/react/components/signup_user_complete.jsx35
-rw-r--r--web/react/components/team_feature_tab.jsx190
-rw-r--r--web/react/components/team_import_tab.jsx2
-rw-r--r--web/react/components/team_settings.jsx14
-rw-r--r--web/react/components/team_settings_modal.jsx13
-rw-r--r--web/react/components/team_signup_choose_auth.jsx20
-rw-r--r--web/react/components/team_signup_password_page.jsx2
-rw-r--r--web/react/components/team_signup_send_invites_page.jsx2
-rw-r--r--web/react/components/team_signup_with_sso.jsx2
-rw-r--r--web/react/components/textbox.jsx53
-rw-r--r--web/react/components/user_profile.jsx2
-rw-r--r--web/react/components/user_settings/custom_theme_chooser.jsx111
-rw-r--r--web/react/components/user_settings/import_theme_modal.jsx179
-rw-r--r--web/react/components/user_settings/manage_incoming_hooks.jsx174
-rw-r--r--web/react/components/user_settings/premade_theme_chooser.jsx58
-rw-r--r--web/react/components/user_settings/user_settings.jsx (renamed from web/react/components/user_settings.jsx)16
-rw-r--r--web/react/components/user_settings/user_settings_appearance.jsx236
-rw-r--r--web/react/components/user_settings/user_settings_developer.jsx (renamed from web/react/components/user_settings_developer.jsx)6
-rw-r--r--web/react/components/user_settings/user_settings_general.jsx (renamed from web/react/components/user_settings_general.jsx)16
-rw-r--r--web/react/components/user_settings/user_settings_integrations.jsx95
-rw-r--r--web/react/components/user_settings/user_settings_modal.jsx (renamed from web/react/components/user_settings_modal.jsx)7
-rw-r--r--web/react/components/user_settings/user_settings_notifications.jsx (renamed from web/react/components/user_settings_notifications.jsx)24
-rw-r--r--web/react/components/user_settings/user_settings_security.jsx (renamed from web/react/components/user_settings_security.jsx)10
-rw-r--r--web/react/components/user_settings_appearance.jsx181
-rw-r--r--web/react/components/view_image.jsx250
-rw-r--r--web/react/components/view_image_popover_bar.jsx66
-rw-r--r--web/react/package.json18
-rw-r--r--web/react/pages/channel.jsx14
-rw-r--r--web/react/pages/login.jsx1
-rw-r--r--web/react/pages/signup_team.jsx6
-rw-r--r--web/react/pages/signup_user_complete.jsx1
-rw-r--r--web/react/pages/verify.jsx1
-rw-r--r--web/react/stores/admin_store.jsx40
-rw-r--r--web/react/stores/error_store.jsx2
-rw-r--r--web/react/stores/socket_store.jsx42
-rw-r--r--web/react/stores/user_store.jsx16
-rw-r--r--web/react/utils/async_client.jsx26
-rw-r--r--web/react/utils/client.jsx216
-rw-r--r--web/react/utils/constants.jsx171
-rw-r--r--web/react/utils/emoticons.jsx158
-rw-r--r--web/react/utils/markdown.jsx44
-rw-r--r--web/react/utils/text_formatting.jsx81
-rw-r--r--web/react/utils/utils.jsx207
-rw-r--r--web/sass-files/sass/partials/_admin-console.scss17
-rw-r--r--web/sass-files/sass/partials/_base.scss21
-rw-r--r--web/sass-files/sass/partials/_colorpicker.scss251
-rw-r--r--web/sass-files/sass/partials/_files.scss9
-rw-r--r--web/sass-files/sass/partials/_forms.scss1
-rw-r--r--web/sass-files/sass/partials/_headers.scss5
-rw-r--r--web/sass-files/sass/partials/_loading.scss2
-rw-r--r--web/sass-files/sass/partials/_markdown.scss67
-rw-r--r--web/sass-files/sass/partials/_mentions.scss9
-rw-r--r--web/sass-files/sass/partials/_modal.scss42
-rw-r--r--web/sass-files/sass/partials/_post.scss16
-rw-r--r--web/sass-files/sass/partials/_search.scss1
-rw-r--r--web/sass-files/sass/partials/_settings.scss45
-rw-r--r--web/sass-files/sass/partials/_sidebar--left.scss6
-rw-r--r--web/sass-files/sass/partials/_sidebar--right.scss11
-rw-r--r--web/sass-files/sass/partials/_videos.scss10
-rw-r--r--web/sass-files/sass/styles.scss2
-rwxr-xr-xweb/static/css/bootstrap-colorpicker.min.css9
-rwxr-xr-xweb/static/images/bootstrap-colorpicker/alpha-horizontal.pngbin0 -> 3635 bytes
-rwxr-xr-xweb/static/images/bootstrap-colorpicker/alpha.pngbin0 -> 3271 bytes
-rwxr-xr-xweb/static/images/bootstrap-colorpicker/hue-horizontal.pngbin0 -> 2837 bytes
-rwxr-xr-xweb/static/images/bootstrap-colorpicker/hue.pngbin0 -> 2972 bytes
-rwxr-xr-xweb/static/images/bootstrap-colorpicker/saturation.pngbin0 -> 8817 bytes
-rw-r--r--web/static/images/themes/mattermost dark.pngbin0 -> 75371 bytes
-rw-r--r--web/static/images/themes/mattermost.pngbin0 -> 66828 bytes
-rw-r--r--web/static/images/themes/organization.pngbin0 -> 86044 bytes
-rw-r--r--web/static/images/themes/slack.pngbin0 -> 68603 bytes
-rw-r--r--web/static/images/themes/windows dark.pngbin0 -> 82784 bytes
-rwxr-xr-xweb/static/js/bootstrap-colorpicker.min.js1
-rwxr-xr-xweb/static/js/emojify.min.js4
-rw-r--r--web/templates/channel.html1
-rw-r--r--web/templates/head.html33
-rw-r--r--web/web.go108
-rw-r--r--web/web_test.go47
246 files changed, 11909 insertions, 7911 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18238d9eb..64cc57ab8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,6 @@
# Mattermost Changelog
-## UNDER DEVELOPMENT - Release v0.8.0 (Beta2)
+## UNDER DEVELOPMENT - Release v1.0.0-RC1
The "UNDER DEVELOPMENT" section of the Mattermost changelog appears in the product's `master` branch to note key changes committed to master and are on their way to the next stable release. When a stable release is pushed the "UNDER DEVELOPMENT" heading is removed from the final changelog of the release.
@@ -9,22 +9,37 @@ The "UNDER DEVELOPMENT" section of the Mattermost changelog appears in the produ
### Release Highlights
-- [See Product Roadmap for anticipated features](https://mattermost.atlassian.net/issues/?filter=10002)
+- System Console - UI for configuring deployments, managing teams, resetting user passwords and other admin features
+- Markdown support in messages, comments and channel descriptions - Including font formatting, emoticons, headings and tables
+- Preset themes and detailed theme color options, plus ability to import themes from Slack
+- Numerous performance improvements and optimizations
### New Features
Messaging, Comments and Notifications
-- (Preview) Added support for emoji codes rendering to image files
+- Support for emoji codes rendering to image files
+- Full markdown support in messages, comments, and channel description
-Admin Console
+Files and Images
-- (Preview) Ability to view server logs and change config settings
+- Added ability to play video and audio files
-Integrations
+System Console
+
+- UI to change config.json settings
+- Ability to view log files from console
+- Ability to reset user passwords
+- Ability for IT admin to manage members across multiple teams from single interface
+
+User Interface
-- (Preview) Added API for incoming webhooks
-- (Preview) Added OAuth2 as a service provider to allow for more secure connection to external apps
+- Ability to set custom theme colors
+- Replaced single color themes with pre-set themes
+- Added ability to import themes from Slack
+
+Integrations
+- (Preview) Initial support for incoming webhooks
### Improvements
@@ -35,6 +50,7 @@ Documentation
- Added Code Contribution Guidelines
- Added new hardware sizing recommendations
- Consolidated licensing information into LICENSE.txt and NOTICE.txt
+- Added markdown documentation
Performance
@@ -46,17 +62,18 @@ Code Quality
UI
-- Added version, build number, build date and build hash under Account Settings -> Security (to be moved to "About" dialog later)
+- Added version, build number, build date and build hash under Account Settings -> Security
### Bug Fixes
-- Fixed performance issue with slow typing on iOS
+- Numerous performance improvements
- Fixed issue so that SSO option automatically set EmailVerified=true (it was false previously)
### Contributors
Many thanks to our external contributors. In no particular order:
+- [jdeng](https://github.com/jdeng)
- [Trozz](https://github.com/Trozz)
- [LAndres](https://github.com/LAndreas)
- [JessBot](https://github.com/JessBot)
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
index d6503a1d5..7c80558c4 100644
--- a/Godeps/Godeps.json
+++ b/Godeps/Godeps.json
@@ -13,11 +13,6 @@
"Rev": "69e2a90ed92d03812364aeb947b7068dc42e561e"
},
{
- "ImportPath": "code.google.com/p/graphics-go/graphics",
- "Comment": "null-25",
- "Rev": "f843bfcd8ac420072c7f6804599995b0a229070b"
- },
- {
"ImportPath": "code.google.com/p/log4go",
"Comment": "go.weekly.2012-02-22-1",
"Rev": "c3294304d93f48a37d3bed1d382882a9c2989f99"
@@ -32,6 +27,10 @@
"Rev": "5280e250f2795914acbeb2bf3b55dd5a2d1fba52"
},
{
+ "ImportPath": "github.com/disintegration/imaging",
+ "Rev": "493653de80c32beeae336f3a3a3a125e7603459b"
+ },
+ {
"ImportPath": "github.com/garyburd/redigo/internal",
"Rev": "a47585eaae68b1d14b02940d2af1b9194f3caa9c"
},
@@ -85,12 +84,8 @@
},
{
"ImportPath": "github.com/mssola/user_agent",
- "Comment": "v0.4.1-2-g35c7f18",
- "Rev": "35c7f18f5261cc18c698a461053c119aebaf8542"
- },
- {
- "ImportPath": "github.com/nfnt/resize",
- "Rev": "dc93e1b98c579d90ee2fa15c1fd6dac34f6e7899"
+ "Comment": "v0.4.1-4-ga163d6a",
+ "Rev": "a163d6a569f1cd264d2f8b2bf3c5d04ace5995eb"
},
{
"ImportPath": "github.com/rwcarlsen/goexif/exif",
@@ -137,6 +132,10 @@
"Rev": "baddd3465a05d84a6d8d3507547a91cb188c81ea"
},
{
+ "ImportPath": "golang.org/x/image/tiff",
+ "Rev": "baddd3465a05d84a6d8d3507547a91cb188c81ea"
+ },
+ {
"ImportPath": "gopkg.in/fsnotify.v1",
"Comment": "v1.2.0",
"Rev": "96c060f6a6b7e0d6f75fddd10efeaca3e5d1bcb0"
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/Makefile b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/Makefile
deleted file mode 100644
index 28a06f0e8..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2011 The Graphics-Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-include $(GOROOT)/src/Make.inc
-
-TARG=code.google.com/p/graphics-go/graphics
-GOFILES=\
- affine.go\
- blur.go\
- rotate.go\
- scale.go\
- thumbnail.go\
-
-include $(GOROOT)/src/Make.pkg
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/affine.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/affine.go
deleted file mode 100644
index 0ac2ec9da..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/affine.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/interp"
- "errors"
- "image"
- "image/draw"
- "math"
-)
-
-// I is the identity Affine transform matrix.
-var I = Affine{
- 1, 0, 0,
- 0, 1, 0,
- 0, 0, 1,
-}
-
-// Affine is a 3x3 2D affine transform matrix.
-// M(i,j) is Affine[i*3+j].
-type Affine [9]float64
-
-// Mul returns the multiplication of two affine transform matrices.
-func (a Affine) Mul(b Affine) Affine {
- return Affine{
- a[0]*b[0] + a[1]*b[3] + a[2]*b[6],
- a[0]*b[1] + a[1]*b[4] + a[2]*b[7],
- a[0]*b[2] + a[1]*b[5] + a[2]*b[8],
- a[3]*b[0] + a[4]*b[3] + a[5]*b[6],
- a[3]*b[1] + a[4]*b[4] + a[5]*b[7],
- a[3]*b[2] + a[4]*b[5] + a[5]*b[8],
- a[6]*b[0] + a[7]*b[3] + a[8]*b[6],
- a[6]*b[1] + a[7]*b[4] + a[8]*b[7],
- a[6]*b[2] + a[7]*b[5] + a[8]*b[8],
- }
-}
-
-func (a Affine) transformRGBA(dst *image.RGBA, src *image.RGBA, i interp.RGBA) error {
- srcb := src.Bounds()
- b := dst.Bounds()
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- sx, sy := a.pt(x, y)
- if inBounds(srcb, sx, sy) {
- c := i.RGBA(src, sx, sy)
- off := (y-dst.Rect.Min.Y)*dst.Stride + (x-dst.Rect.Min.X)*4
- dst.Pix[off+0] = c.R
- dst.Pix[off+1] = c.G
- dst.Pix[off+2] = c.B
- dst.Pix[off+3] = c.A
- }
- }
- }
- return nil
-}
-
-// Transform applies the affine transform to src and produces dst.
-func (a Affine) Transform(dst draw.Image, src image.Image, i interp.Interp) error {
- if dst == nil {
- return errors.New("graphics: dst is nil")
- }
- if src == nil {
- return errors.New("graphics: src is nil")
- }
-
- // RGBA fast path.
- dstRGBA, dstOk := dst.(*image.RGBA)
- srcRGBA, srcOk := src.(*image.RGBA)
- interpRGBA, interpOk := i.(interp.RGBA)
- if dstOk && srcOk && interpOk {
- return a.transformRGBA(dstRGBA, srcRGBA, interpRGBA)
- }
-
- srcb := src.Bounds()
- b := dst.Bounds()
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- sx, sy := a.pt(x, y)
- if inBounds(srcb, sx, sy) {
- dst.Set(x, y, i.Interp(src, sx, sy))
- }
- }
- }
- return nil
-}
-
-func inBounds(b image.Rectangle, x, y float64) bool {
- if x < float64(b.Min.X) || x >= float64(b.Max.X) {
- return false
- }
- if y < float64(b.Min.Y) || y >= float64(b.Max.Y) {
- return false
- }
- return true
-}
-
-func (a Affine) pt(x0, y0 int) (x1, y1 float64) {
- fx := float64(x0) + 0.5
- fy := float64(y0) + 0.5
- x1 = fx*a[0] + fy*a[1] + a[2]
- y1 = fx*a[3] + fy*a[4] + a[5]
- return x1, y1
-}
-
-// TransformCenter applies the affine transform to src and produces dst.
-// Equivalent to
-// a.CenterFit(dst, src).Transform(dst, src, i).
-func (a Affine) TransformCenter(dst draw.Image, src image.Image, i interp.Interp) error {
- if dst == nil {
- return errors.New("graphics: dst is nil")
- }
- if src == nil {
- return errors.New("graphics: src is nil")
- }
-
- return a.CenterFit(dst.Bounds(), src.Bounds()).Transform(dst, src, i)
-}
-
-// Scale produces a scaling transform of factors x and y.
-func (a Affine) Scale(x, y float64) Affine {
- return a.Mul(Affine{
- 1 / x, 0, 0,
- 0, 1 / y, 0,
- 0, 0, 1,
- })
-}
-
-// Rotate produces a clockwise rotation transform of angle, in radians.
-func (a Affine) Rotate(angle float64) Affine {
- s, c := math.Sincos(angle)
- return a.Mul(Affine{
- +c, +s, +0,
- -s, +c, +0,
- +0, +0, +1,
- })
-}
-
-// Shear produces a shear transform by the slopes x and y.
-func (a Affine) Shear(x, y float64) Affine {
- d := 1 - x*y
- return a.Mul(Affine{
- +1 / d, -x / d, 0,
- -y / d, +1 / d, 0,
- 0, 0, 1,
- })
-}
-
-// Translate produces a translation transform with pixel distances x and y.
-func (a Affine) Translate(x, y float64) Affine {
- return a.Mul(Affine{
- 1, 0, -x,
- 0, 1, -y,
- 0, 0, +1,
- })
-}
-
-// Center produces the affine transform, centered around the provided point.
-func (a Affine) Center(x, y float64) Affine {
- return I.Translate(-x, -y).Mul(a).Translate(x, y)
-}
-
-// CenterFit produces the affine transform, centered around the rectangles.
-// It is equivalent to
-// I.Translate(-<center of src>).Mul(a).Translate(<center of dst>)
-func (a Affine) CenterFit(dst, src image.Rectangle) Affine {
- dx := float64(dst.Min.X) + float64(dst.Dx())/2
- dy := float64(dst.Min.Y) + float64(dst.Dy())/2
- sx := float64(src.Min.X) + float64(src.Dx())/2
- sy := float64(src.Min.Y) + float64(src.Dy())/2
- return I.Translate(-sx, -sy).Mul(a).Translate(dx, dy)
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur.go
deleted file mode 100644
index 9a54d5ad5..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/convolve"
- "errors"
- "image"
- "image/draw"
- "math"
-)
-
-// DefaultStdDev is the default blurring parameter.
-var DefaultStdDev = 0.5
-
-// BlurOptions are the blurring parameters.
-// StdDev is the standard deviation of the normal, higher is blurrier.
-// Size is the size of the kernel. If zero, it is set to Ceil(6 * StdDev).
-type BlurOptions struct {
- StdDev float64
- Size int
-}
-
-// Blur produces a blurred version of the image, using a Gaussian blur.
-func Blur(dst draw.Image, src image.Image, opt *BlurOptions) error {
- if dst == nil {
- return errors.New("graphics: dst is nil")
- }
- if src == nil {
- return errors.New("graphics: src is nil")
- }
-
- sd := DefaultStdDev
- size := 0
-
- if opt != nil {
- sd = opt.StdDev
- size = opt.Size
- }
-
- if size < 1 {
- size = int(math.Ceil(sd * 6))
- }
-
- kernel := make([]float64, 2*size+1)
- for i := 0; i <= size; i++ {
- x := float64(i) / sd
- x = math.Pow(1/math.SqrtE, x*x)
- kernel[size-i] = x
- kernel[size+i] = x
- }
-
- // Normalize the weights to sum to 1.0.
- kSum := 0.0
- for _, k := range kernel {
- kSum += k
- }
- for i, k := range kernel {
- kernel[i] = k / kSum
- }
-
- return convolve.Convolve(dst, src, &convolve.SeparableKernel{
- X: kernel,
- Y: kernel,
- })
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur_test.go
deleted file mode 100644
index 1d84fa604..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/blur_test.go
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "image/color"
- "testing"
-
- _ "image/png"
-)
-
-var blurOneColorTests = []transformOneColorTest{
- {
- "1x1-blank", 1, 1, 1, 1,
- &BlurOptions{0.83, 1},
- []uint8{0xff},
- []uint8{0xff},
- },
- {
- "1x1-spreadblank", 1, 1, 1, 1,
- &BlurOptions{0.83, 2},
- []uint8{0xff},
- []uint8{0xff},
- },
- {
- "3x3-blank", 3, 3, 3, 3,
- &BlurOptions{0.83, 2},
- []uint8{
- 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff,
- },
- []uint8{
- 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff,
- },
- },
- {
- "3x3-dot", 3, 3, 3, 3,
- &BlurOptions{0.34, 1},
- []uint8{
- 0x00, 0x00, 0x00,
- 0x00, 0xff, 0x00,
- 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x03, 0x00,
- 0x03, 0xf2, 0x03,
- 0x00, 0x03, 0x00,
- },
- },
- {
- "5x5-dot", 5, 5, 5, 5,
- &BlurOptions{0.34, 1},
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x03, 0x00, 0x00,
- 0x00, 0x03, 0xf2, 0x03, 0x00,
- 0x00, 0x00, 0x03, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- },
- {
- "5x5-dot-spread", 5, 5, 5, 5,
- &BlurOptions{0.85, 1},
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x10, 0x20, 0x10, 0x00,
- 0x00, 0x20, 0x40, 0x20, 0x00,
- 0x00, 0x10, 0x20, 0x10, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- },
- {
- "4x4-box", 4, 4, 4, 4,
- &BlurOptions{0.34, 1},
- []uint8{
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0xff, 0xff, 0x00,
- 0x00, 0xff, 0xff, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x03, 0x03, 0x00,
- 0x03, 0xf8, 0xf8, 0x03,
- 0x03, 0xf8, 0xf8, 0x03,
- 0x00, 0x03, 0x03, 0x00,
- },
- },
- {
- "5x5-twodots", 5, 5, 5, 5,
- &BlurOptions{0.34, 1},
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x96, 0x00, 0x96, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x02, 0x00, 0x02, 0x00,
- 0x02, 0x8e, 0x04, 0x8e, 0x02,
- 0x00, 0x02, 0x00, 0x02, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00,
- },
- },
-}
-
-func TestBlurOneColor(t *testing.T) {
- for _, oc := range blurOneColorTests {
- dst := oc.newDst()
- src := oc.newSrc()
- opt := oc.opt.(*BlurOptions)
- if err := Blur(dst, src, opt); err != nil {
- t.Fatal(err)
- }
-
- if !checkTransformTest(t, &oc, dst) {
- continue
- }
- }
-}
-
-func TestBlurEmpty(t *testing.T) {
- empty := image.NewRGBA(image.Rect(0, 0, 0, 0))
- if err := Blur(empty, empty, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestBlurGopher(t *testing.T) {
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
-
- dst := image.NewRGBA(src.Bounds())
- if err = Blur(dst, src, &BlurOptions{StdDev: 1.1}); err != nil {
- t.Fatal(err)
- }
-
- cmp, err := graphicstest.LoadImage("../testdata/gopher-blur.png")
- if err != nil {
- t.Fatal(err)
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0x101)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func benchBlur(b *testing.B, bounds image.Rectangle) {
- b.StopTimer()
-
- // Construct a fuzzy image.
- src := image.NewRGBA(bounds)
- for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
- for x := bounds.Min.X; x < bounds.Max.X; x++ {
- src.SetRGBA(x, y, color.RGBA{
- uint8(5 * x % 0x100),
- uint8(7 * y % 0x100),
- uint8((7*x + 5*y) % 0x100),
- 0xff,
- })
- }
- }
- dst := image.NewRGBA(bounds)
-
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- Blur(dst, src, &BlurOptions{0.84, 3})
- }
-}
-
-func BenchmarkBlur400x400x3(b *testing.B) {
- benchBlur(b, image.Rect(0, 0, 400, 400))
-}
-
-// Exactly twice the pixel count of 400x400.
-func BenchmarkBlur400x800x3(b *testing.B) {
- benchBlur(b, image.Rect(0, 0, 400, 800))
-}
-
-// Exactly twice the pixel count of 400x800
-func BenchmarkBlur400x1600x3(b *testing.B) {
- benchBlur(b, image.Rect(0, 0, 400, 1600))
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/Makefile b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/Makefile
deleted file mode 100644
index a5691fa30..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/Makefile
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright 2011 The Graphics-Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-include $(GOROOT)/src/Make.inc
-
-TARG=code.google.com/p/graphics-go/graphics/convolve
-GOFILES=\
- convolve.go\
-
-include $(GOROOT)/src/Make.pkg
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve.go
deleted file mode 100644
index da69496d0..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve.go
+++ /dev/null
@@ -1,274 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package convolve
-
-import (
- "errors"
- "fmt"
- "image"
- "image/draw"
- "math"
-)
-
-// clamp clamps x to the range [x0, x1].
-func clamp(x, x0, x1 float64) float64 {
- if x < x0 {
- return x0
- }
- if x > x1 {
- return x1
- }
- return x
-}
-
-// Kernel is a square matrix that defines a convolution.
-type Kernel interface {
- // Weights returns the square matrix of weights in row major order.
- Weights() []float64
-}
-
-// SeparableKernel is a linearly separable, square convolution kernel.
-// X and Y are the per-axis weights. Each slice must be the same length, and
-// have an odd length. The middle element of each slice is the weight for the
-// central pixel. For example, the horizontal Sobel kernel is:
-// sobelX := &SeparableKernel{
-// X: []float64{-1, 0, +1},
-// Y: []float64{1, 2, 1},
-// }
-type SeparableKernel struct {
- X, Y []float64
-}
-
-func (k *SeparableKernel) Weights() []float64 {
- n := len(k.X)
- w := make([]float64, n*n)
- for y := 0; y < n; y++ {
- for x := 0; x < n; x++ {
- w[y*n+x] = k.X[x] * k.Y[y]
- }
- }
- return w
-}
-
-// fullKernel is a square convolution kernel.
-type fullKernel []float64
-
-func (k fullKernel) Weights() []float64 { return k }
-
-func kernelSize(w []float64) (size int, err error) {
- size = int(math.Sqrt(float64(len(w))))
- if size*size != len(w) {
- return 0, errors.New("graphics: kernel is not square")
- }
- if size%2 != 1 {
- return 0, errors.New("graphics: kernel size is not odd")
- }
- return size, nil
-}
-
-// NewKernel returns a square convolution kernel.
-func NewKernel(w []float64) (Kernel, error) {
- if _, err := kernelSize(w); err != nil {
- return nil, err
- }
- return fullKernel(w), nil
-}
-
-func convolveRGBASep(dst *image.RGBA, src image.Image, k *SeparableKernel) error {
- if len(k.X) != len(k.Y) {
- return fmt.Errorf("graphics: kernel not square (x %d, y %d)", len(k.X), len(k.Y))
- }
- if len(k.X)%2 != 1 {
- return fmt.Errorf("graphics: kernel length (%d) not odd", len(k.X))
- }
- radius := (len(k.X) - 1) / 2
-
- // buf holds the result of vertically blurring src.
- bounds := dst.Bounds()
- width, height := bounds.Dx(), bounds.Dy()
- buf := make([]float64, width*height*4)
- for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
- for x := bounds.Min.X; x < bounds.Max.X; x++ {
- var r, g, b, a float64
- // k0 is the kernel weight for the center pixel. This may be greater
- // than kernel[0], near the boundary of the source image, to avoid
- // vignetting.
- k0 := k.X[radius]
-
- // Add the pixels from above.
- for i := 1; i <= radius; i++ {
- f := k.Y[radius-i]
- if y-i < bounds.Min.Y {
- k0 += f
- } else {
- or, og, ob, oa := src.At(x, y-i).RGBA()
- r += float64(or>>8) * f
- g += float64(og>>8) * f
- b += float64(ob>>8) * f
- a += float64(oa>>8) * f
- }
- }
-
- // Add the pixels from below.
- for i := 1; i <= radius; i++ {
- f := k.Y[radius+i]
- if y+i >= bounds.Max.Y {
- k0 += f
- } else {
- or, og, ob, oa := src.At(x, y+i).RGBA()
- r += float64(or>>8) * f
- g += float64(og>>8) * f
- b += float64(ob>>8) * f
- a += float64(oa>>8) * f
- }
- }
-
- // Add the central pixel.
- or, og, ob, oa := src.At(x, y).RGBA()
- r += float64(or>>8) * k0
- g += float64(og>>8) * k0
- b += float64(ob>>8) * k0
- a += float64(oa>>8) * k0
-
- // Write to buf.
- o := (y-bounds.Min.Y)*width*4 + (x-bounds.Min.X)*4
- buf[o+0] = r
- buf[o+1] = g
- buf[o+2] = b
- buf[o+3] = a
- }
- }
-
- // dst holds the result of horizontally blurring buf.
- for y := 0; y < height; y++ {
- for x := 0; x < width; x++ {
- var r, g, b, a float64
- k0, off := k.X[radius], y*width*4+x*4
-
- // Add the pixels from the left.
- for i := 1; i <= radius; i++ {
- f := k.X[radius-i]
- if x-i < 0 {
- k0 += f
- } else {
- o := off - i*4
- r += buf[o+0] * f
- g += buf[o+1] * f
- b += buf[o+2] * f
- a += buf[o+3] * f
- }
- }
-
- // Add the pixels from the right.
- for i := 1; i <= radius; i++ {
- f := k.X[radius+i]
- if x+i >= width {
- k0 += f
- } else {
- o := off + i*4
- r += buf[o+0] * f
- g += buf[o+1] * f
- b += buf[o+2] * f
- a += buf[o+3] * f
- }
- }
-
- // Add the central pixel.
- r += buf[off+0] * k0
- g += buf[off+1] * k0
- b += buf[off+2] * k0
- a += buf[off+3] * k0
-
- // Write to dst, clamping to the range [0, 255].
- dstOff := (y-dst.Rect.Min.Y)*dst.Stride + (x-dst.Rect.Min.X)*4
- dst.Pix[dstOff+0] = uint8(clamp(r+0.5, 0, 255))
- dst.Pix[dstOff+1] = uint8(clamp(g+0.5, 0, 255))
- dst.Pix[dstOff+2] = uint8(clamp(b+0.5, 0, 255))
- dst.Pix[dstOff+3] = uint8(clamp(a+0.5, 0, 255))
- }
- }
-
- return nil
-}
-
-func convolveRGBA(dst *image.RGBA, src image.Image, k Kernel) error {
- b := dst.Bounds()
- bs := src.Bounds()
- w := k.Weights()
- size, err := kernelSize(w)
- if err != nil {
- return err
- }
- radius := (size - 1) / 2
-
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- if !image.Pt(x, y).In(bs) {
- continue
- }
-
- var r, g, b, a, adj float64
- for cy := y - radius; cy <= y+radius; cy++ {
- for cx := x - radius; cx <= x+radius; cx++ {
- factor := w[(cy-y+radius)*size+cx-x+radius]
- if !image.Pt(cx, cy).In(bs) {
- adj += factor
- } else {
- sr, sg, sb, sa := src.At(cx, cy).RGBA()
- r += float64(sr>>8) * factor
- g += float64(sg>>8) * factor
- b += float64(sb>>8) * factor
- a += float64(sa>>8) * factor
- }
- }
- }
-
- if adj != 0 {
- sr, sg, sb, sa := src.At(x, y).RGBA()
- r += float64(sr>>8) * adj
- g += float64(sg>>8) * adj
- b += float64(sb>>8) * adj
- a += float64(sa>>8) * adj
- }
-
- off := (y-dst.Rect.Min.Y)*dst.Stride + (x-dst.Rect.Min.X)*4
- dst.Pix[off+0] = uint8(clamp(r+0.5, 0, 0xff))
- dst.Pix[off+1] = uint8(clamp(g+0.5, 0, 0xff))
- dst.Pix[off+2] = uint8(clamp(b+0.5, 0, 0xff))
- dst.Pix[off+3] = uint8(clamp(a+0.5, 0, 0xff))
- }
- }
-
- return nil
-}
-
-// Convolve produces dst by applying the convolution kernel k to src.
-func Convolve(dst draw.Image, src image.Image, k Kernel) (err error) {
- if dst == nil || src == nil || k == nil {
- return nil
- }
-
- b := dst.Bounds()
- dstRgba, ok := dst.(*image.RGBA)
- if !ok {
- dstRgba = image.NewRGBA(b)
- }
-
- switch k := k.(type) {
- case *SeparableKernel:
- err = convolveRGBASep(dstRgba, src, k)
- default:
- err = convolveRGBA(dstRgba, src, k)
- }
-
- if err != nil {
- return err
- }
-
- if !ok {
- draw.Draw(dst, b, dstRgba, b.Min, draw.Src)
- }
- return nil
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve_test.go
deleted file mode 100644
index f34d7afc8..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/convolve/convolve_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package convolve
-
-import (
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "reflect"
- "testing"
-
- _ "image/png"
-)
-
-func TestSeparableWeights(t *testing.T) {
- sobelXFull := []float64{
- -1, 0, 1,
- -2, 0, 2,
- -1, 0, 1,
- }
- sobelXSep := &SeparableKernel{
- X: []float64{-1, 0, +1},
- Y: []float64{1, 2, 1},
- }
- w := sobelXSep.Weights()
- if !reflect.DeepEqual(w, sobelXFull) {
- t.Errorf("got %v want %v", w, sobelXFull)
- }
-}
-
-func TestConvolve(t *testing.T) {
- kernFull, err := NewKernel([]float64{
- 0, 0, 0,
- 1, 1, 1,
- 0, 0, 0,
- })
- if err != nil {
- t.Fatal(err)
- }
-
- kernSep := &SeparableKernel{
- X: []float64{1, 1, 1},
- Y: []float64{0, 1, 0},
- }
-
- src, err := graphicstest.LoadImage("../../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
- b := src.Bounds()
-
- sep := image.NewRGBA(b)
- if err = Convolve(sep, src, kernSep); err != nil {
- t.Fatal(err)
- }
-
- full := image.NewRGBA(b)
- Convolve(full, src, kernFull)
-
- err = graphicstest.ImageWithinTolerance(sep, full, 0x101)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestConvolveNil(t *testing.T) {
- if err := Convolve(nil, nil, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestConvolveEmpty(t *testing.T) {
- empty := image.NewRGBA(image.Rect(0, 0, 0, 0))
- if err := Convolve(empty, empty, nil); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/Makefile b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/Makefile
deleted file mode 100644
index 0b1c6cb3e..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2011 The Graphics-Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-include $(GOROOT)/src/Make.inc
-
-TARG=code.google.com/p/graphics-go/graphics
-GOFILES=\
- detect.go\
- doc.go\
- integral.go\
- opencv_parser.go\
- projector.go\
-
-include $(GOROOT)/src/Make.pkg
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect.go
deleted file mode 100644
index dde941cbe..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect.go
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
- "math"
-)
-
-// Feature is a Haar-like feature.
-type Feature struct {
- Rect image.Rectangle
- Weight float64
-}
-
-// Classifier is a set of features with a threshold.
-type Classifier struct {
- Feature []Feature
- Threshold float64
- Left float64
- Right float64
-}
-
-// CascadeStage is a cascade of classifiers.
-type CascadeStage struct {
- Classifier []Classifier
- Threshold float64
-}
-
-// Cascade is a degenerate tree of Haar-like classifiers.
-type Cascade struct {
- Stage []CascadeStage
- Size image.Point
-}
-
-// Match returns true if the full image is classified as an object.
-func (c *Cascade) Match(m image.Image) bool {
- return c.classify(newWindow(m))
-}
-
-// Find returns a set of areas of m that match the feature cascade c.
-func (c *Cascade) Find(m image.Image) []image.Rectangle {
- // TODO(crawshaw): Consider de-duping strategies.
- matches := []image.Rectangle{}
- w := newWindow(m)
-
- b := m.Bounds()
- origScale := c.Size
- for s := origScale; s.X < b.Dx() && s.Y < b.Dy(); s = s.Add(s.Div(10)) {
- // translate region and classify
- tx := image.Pt(s.X/10, 0)
- ty := image.Pt(0, s.Y/10)
- for r := image.Rect(0, 0, s.X, s.Y).Add(b.Min); r.In(b); r = r.Add(ty) {
- for r1 := r; r1.In(b); r1 = r1.Add(tx) {
- if c.classify(w.subWindow(r1)) {
- matches = append(matches, r1)
- }
- }
- }
- }
- return matches
-}
-
-type window struct {
- mi *integral
- miSq *integral
- rect image.Rectangle
- invArea float64
- stdDev float64
-}
-
-func (w *window) init() {
- w.invArea = 1 / float64(w.rect.Dx()*w.rect.Dy())
- mean := float64(w.mi.sum(w.rect)) * w.invArea
- vr := float64(w.miSq.sum(w.rect))*w.invArea - mean*mean
- if vr < 0 {
- vr = 1
- }
- w.stdDev = math.Sqrt(vr)
-}
-
-func newWindow(m image.Image) *window {
- mi, miSq := newIntegrals(m)
- res := &window{
- mi: mi,
- miSq: miSq,
- rect: m.Bounds(),
- }
- res.init()
- return res
-}
-
-func (w *window) subWindow(r image.Rectangle) *window {
- res := &window{
- mi: w.mi,
- miSq: w.miSq,
- rect: r,
- }
- res.init()
- return res
-}
-
-func (c *Classifier) classify(w *window, pr *projector) float64 {
- s := 0.0
- for _, f := range c.Feature {
- s += float64(w.mi.sum(pr.rect(f.Rect))) * f.Weight
- }
- s *= w.invArea // normalize to maintain scale invariance
- if s < c.Threshold*w.stdDev {
- return c.Left
- }
- return c.Right
-}
-
-func (s *CascadeStage) classify(w *window, pr *projector) bool {
- sum := 0.0
- for _, c := range s.Classifier {
- sum += c.classify(w, pr)
- }
- return sum >= s.Threshold
-}
-
-func (c *Cascade) classify(w *window) bool {
- pr := newProjector(w.rect, image.Rectangle{image.Pt(0, 0), c.Size})
- for _, s := range c.Stage {
- if !s.classify(w, pr) {
- return false
- }
- }
- return true
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect_test.go
deleted file mode 100644
index 8a2df113d..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/detect_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
- "image/draw"
- "testing"
-)
-
-var (
- c0 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(0, 0, 3, 4), Weight: 4.0},
- },
- Threshold: 0.2,
- Left: 0.8,
- Right: 0.2,
- }
- c1 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(3, 4, 4, 5), Weight: 4.0},
- },
- Threshold: 0.2,
- Left: 0.8,
- Right: 0.2,
- }
- c2 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(0, 0, 1, 1), Weight: +4.0},
- Feature{Rect: image.Rect(0, 0, 2, 2), Weight: -1.0},
- },
- Threshold: 0.2,
- Left: 0.8,
- Right: 0.2,
- }
-)
-
-func TestClassifier(t *testing.T) {
- m := image.NewGray(image.Rect(0, 0, 20, 20))
- b := m.Bounds()
- draw.Draw(m, image.Rect(0, 0, 20, 20), image.White, image.ZP, draw.Src)
- draw.Draw(m, image.Rect(3, 4, 4, 5), image.Black, image.ZP, draw.Src)
- w := newWindow(m)
- pr := newProjector(b, b)
-
- if res := c0.classify(w, pr); res != c0.Right {
- t.Errorf("c0 got %f want %f", res, c0.Right)
- }
- if res := c1.classify(w, pr); res != c1.Left {
- t.Errorf("c1 got %f want %f", res, c1.Left)
- }
- if res := c2.classify(w, pr); res != c1.Left {
- t.Errorf("c2 got %f want %f", res, c1.Left)
- }
-}
-
-func TestClassifierScale(t *testing.T) {
- m := image.NewGray(image.Rect(0, 0, 50, 50))
- b := m.Bounds()
- draw.Draw(m, image.Rect(0, 0, 8, 10), image.White, b.Min, draw.Src)
- draw.Draw(m, image.Rect(8, 10, 10, 13), image.Black, b.Min, draw.Src)
- w := newWindow(m)
- pr := newProjector(b, image.Rect(0, 0, 20, 20))
-
- if res := c0.classify(w, pr); res != c0.Right {
- t.Errorf("scaled c0 got %f want %f", res, c0.Right)
- }
- if res := c1.classify(w, pr); res != c1.Left {
- t.Errorf("scaled c1 got %f want %f", res, c1.Left)
- }
- if res := c2.classify(w, pr); res != c1.Left {
- t.Errorf("scaled c2 got %f want %f", res, c1.Left)
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/doc.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/doc.go
deleted file mode 100644
index a0f4e94cd..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/doc.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package detect implements an object detector cascade.
-
-The technique used is a degenerate tree of Haar-like classifiers, commonly
-used for face detection. It is described in
-
- P. Viola, M. Jones.
- Rapid Object Detection using a Boosted Cascade of Simple Features, 2001
- IEEE Conference on Computer Vision and Pattern Recognition
-
-A Cascade can be constructed manually from a set of Classifiers in stages,
-or can be loaded from an XML file in the OpenCV format with
-
- classifier, _, err := detect.ParseOpenCV(r)
-
-The classifier can be used to determine if a full image is detected as an
-object using Detect
-
- if classifier.Match(m) {
- // m is an image of a face.
- }
-
-It is also possible to search an image for occurrences of an object
-
- objs := classifier.Find(m)
-*/
-package detect
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral.go
deleted file mode 100644
index 814ced590..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
- "image/draw"
-)
-
-// integral is an image.Image-like structure that stores the cumulative
-// sum of the preceding pixels. This allows for O(1) summation of any
-// rectangular region within the image.
-type integral struct {
- // pix holds the cumulative sum of the image's pixels. The pixel at
- // (x, y) starts at pix[(y-rect.Min.Y)*stride + (x-rect.Min.X)*1].
- pix []uint64
- stride int
- rect image.Rectangle
-}
-
-func (p *integral) at(x, y int) uint64 {
- return p.pix[(y-p.rect.Min.Y)*p.stride+(x-p.rect.Min.X)]
-}
-
-func (p *integral) sum(b image.Rectangle) uint64 {
- c := p.at(b.Max.X-1, b.Max.Y-1)
- inY := b.Min.Y > p.rect.Min.Y
- inX := b.Min.X > p.rect.Min.X
- if inY && inX {
- c += p.at(b.Min.X-1, b.Min.Y-1)
- }
- if inY {
- c -= p.at(b.Max.X-1, b.Min.Y-1)
- }
- if inX {
- c -= p.at(b.Min.X-1, b.Max.Y-1)
- }
- return c
-}
-
-func (m *integral) integrate() {
- b := m.rect
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- c := uint64(0)
- if y > b.Min.Y && x > b.Min.X {
- c += m.at(x-1, y)
- c += m.at(x, y-1)
- c -= m.at(x-1, y-1)
- } else if y > b.Min.Y {
- c += m.at(b.Min.X, y-1)
- } else if x > b.Min.X {
- c += m.at(x-1, b.Min.Y)
- }
- m.pix[(y-m.rect.Min.Y)*m.stride+(x-m.rect.Min.X)] += c
- }
- }
-}
-
-// newIntegrals returns the integral and the squared integral.
-func newIntegrals(src image.Image) (*integral, *integral) {
- b := src.Bounds()
- srcg, ok := src.(*image.Gray)
- if !ok {
- srcg = image.NewGray(b)
- draw.Draw(srcg, b, src, b.Min, draw.Src)
- }
-
- m := integral{
- pix: make([]uint64, b.Max.Y*b.Max.X),
- stride: b.Max.X,
- rect: b,
- }
- mSq := integral{
- pix: make([]uint64, b.Max.Y*b.Max.X),
- stride: b.Max.X,
- rect: b,
- }
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- os := (y-b.Min.Y)*srcg.Stride + x - b.Min.X
- om := (y-b.Min.Y)*m.stride + x - b.Min.X
- c := uint64(srcg.Pix[os])
- m.pix[om] = c
- mSq.pix[om] = c * c
- }
- }
- m.integrate()
- mSq.integrate()
- return &m, &mSq
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral_test.go
deleted file mode 100644
index 0bc321a4d..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/integral_test.go
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "bytes"
- "fmt"
- "image"
- "testing"
-)
-
-type integralTest struct {
- x int
- y int
- src []uint8
- res []uint8
-}
-
-var integralTests = []integralTest{
- {
- 1, 1,
- []uint8{0x01},
- []uint8{0x01},
- },
- {
- 2, 2,
- []uint8{
- 0x01, 0x02,
- 0x03, 0x04,
- },
- []uint8{
- 0x01, 0x03,
- 0x04, 0x0a,
- },
- },
- {
- 4, 4,
- []uint8{
- 0x02, 0x03, 0x00, 0x01,
- 0x01, 0x02, 0x01, 0x05,
- 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01,
- },
- []uint8{
- 0x02, 0x05, 0x05, 0x06,
- 0x03, 0x08, 0x09, 0x0f,
- 0x04, 0x0a, 0x0c, 0x13,
- 0x05, 0x0c, 0x0f, 0x17,
- },
- },
-}
-
-func sprintBox(box []byte, width, height int) string {
- buf := bytes.NewBuffer(nil)
- i := 0
- for y := 0; y < height; y++ {
- for x := 0; x < width; x++ {
- fmt.Fprintf(buf, " 0x%02x,", box[i])
- i++
- }
- buf.WriteByte('\n')
- }
- return buf.String()
-}
-
-func TestIntegral(t *testing.T) {
- for i, oc := range integralTests {
- src := &image.Gray{
- Pix: oc.src,
- Stride: oc.x,
- Rect: image.Rect(0, 0, oc.x, oc.y),
- }
- dst, _ := newIntegrals(src)
- res := make([]byte, len(dst.pix))
- for i, p := range dst.pix {
- res[i] = byte(p)
- }
-
- if !bytes.Equal(res, oc.res) {
- got := sprintBox(res, oc.x, oc.y)
- want := sprintBox(oc.res, oc.x, oc.y)
- t.Errorf("%d: got\n%s\n want\n%s", i, got, want)
- }
- }
-}
-
-func TestIntegralSum(t *testing.T) {
- src := &image.Gray{
- Pix: []uint8{
- 0x02, 0x03, 0x00, 0x01, 0x03,
- 0x01, 0x02, 0x01, 0x05, 0x05,
- 0x01, 0x01, 0x01, 0x01, 0x02,
- 0x01, 0x01, 0x01, 0x01, 0x07,
- 0x02, 0x01, 0x00, 0x03, 0x01,
- },
- Stride: 5,
- Rect: image.Rect(0, 0, 5, 5),
- }
- img, _ := newIntegrals(src)
-
- type sumTest struct {
- rect image.Rectangle
- sum uint64
- }
-
- var sumTests = []sumTest{
- {image.Rect(0, 0, 1, 1), 2},
- {image.Rect(0, 0, 2, 1), 5},
- {image.Rect(0, 0, 1, 3), 4},
- {image.Rect(1, 1, 3, 3), 5},
- {image.Rect(2, 2, 4, 4), 4},
- {image.Rect(4, 3, 5, 5), 8},
- {image.Rect(2, 4, 3, 5), 0},
- }
-
- for _, st := range sumTests {
- s := img.sum(st.rect)
- if s != st.sum {
- t.Errorf("%v: got %d want %d", st.rect, s, st.sum)
- return
- }
- }
-}
-
-func TestIntegralSubImage(t *testing.T) {
- m0 := &image.Gray{
- Pix: []uint8{
- 0x02, 0x03, 0x00, 0x01, 0x03,
- 0x01, 0x02, 0x01, 0x05, 0x05,
- 0x01, 0x04, 0x01, 0x01, 0x02,
- 0x01, 0x02, 0x01, 0x01, 0x07,
- 0x02, 0x01, 0x09, 0x03, 0x01,
- },
- Stride: 5,
- Rect: image.Rect(0, 0, 5, 5),
- }
- b := image.Rect(1, 1, 4, 4)
- m1 := m0.SubImage(b)
- mi0, _ := newIntegrals(m0)
- mi1, _ := newIntegrals(m1)
-
- sum0 := mi0.sum(b)
- sum1 := mi1.sum(b)
- if sum0 != sum1 {
- t.Errorf("b got %d want %d", sum0, sum1)
- }
-
- r0 := image.Rect(2, 2, 4, 4)
- sum0 = mi0.sum(r0)
- sum1 = mi1.sum(r0)
- if sum0 != sum1 {
- t.Errorf("r0 got %d want %d", sum1, sum0)
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser.go
deleted file mode 100644
index 51ded1a1c..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "bytes"
- "encoding/xml"
- "errors"
- "fmt"
- "image"
- "io"
- "io/ioutil"
- "strconv"
- "strings"
-)
-
-type xmlFeature struct {
- Rects []string `xml:"grp>feature>rects>grp"`
- Tilted int `xml:"grp>feature>tilted"`
- Threshold float64 `xml:"grp>threshold"`
- Left float64 `xml:"grp>left_val"`
- Right float64 `xml:"grp>right_val"`
-}
-
-type xmlStages struct {
- Trees []xmlFeature `xml:"trees>grp"`
- Stage_threshold float64 `xml:"stage_threshold"`
- Parent int `xml:"parent"`
- Next int `xml:"next"`
-}
-
-type opencv_storage struct {
- Any struct {
- XMLName xml.Name
- Type string `xml:"type_id,attr"`
- Size string `xml:"size"`
- Stages []xmlStages `xml:"stages>grp"`
- } `xml:",any"`
-}
-
-func buildFeature(r string) (f Feature, err error) {
- var x, y, w, h int
- var weight float64
- _, err = fmt.Sscanf(r, "%d %d %d %d %f", &x, &y, &w, &h, &weight)
- if err != nil {
- return
- }
- f.Rect = image.Rect(x, y, x+w, y+h)
- f.Weight = weight
- return
-}
-
-func buildCascade(s *opencv_storage) (c *Cascade, name string, err error) {
- if s.Any.Type != "opencv-haar-classifier" {
- err = fmt.Errorf("got %s want opencv-haar-classifier", s.Any.Type)
- return
- }
- name = s.Any.XMLName.Local
-
- c = &Cascade{}
- sizes := strings.Split(s.Any.Size, " ")
- w, err := strconv.Atoi(sizes[0])
- if err != nil {
- return nil, "", err
- }
- h, err := strconv.Atoi(sizes[1])
- if err != nil {
- return nil, "", err
- }
- c.Size = image.Pt(w, h)
- c.Stage = []CascadeStage{}
-
- for _, stage := range s.Any.Stages {
- cs := CascadeStage{
- Classifier: []Classifier{},
- Threshold: stage.Stage_threshold,
- }
- for _, tree := range stage.Trees {
- if tree.Tilted != 0 {
- err = errors.New("Cascade does not support tilted features")
- return
- }
-
- cls := Classifier{
- Feature: []Feature{},
- Threshold: tree.Threshold,
- Left: tree.Left,
- Right: tree.Right,
- }
-
- for _, rect := range tree.Rects {
- f, err := buildFeature(rect)
- if err != nil {
- return nil, "", err
- }
- cls.Feature = append(cls.Feature, f)
- }
-
- cs.Classifier = append(cs.Classifier, cls)
- }
- c.Stage = append(c.Stage, cs)
- }
-
- return
-}
-
-// ParseOpenCV produces a detection Cascade from an OpenCV XML file.
-func ParseOpenCV(r io.Reader) (cascade *Cascade, name string, err error) {
- // BUG(crawshaw): tag-based parsing doesn't seem to work with <_>
- buf, err := ioutil.ReadAll(r)
- if err != nil {
- return
- }
- buf = bytes.Replace(buf, []byte("<_>"), []byte("<grp>"), -1)
- buf = bytes.Replace(buf, []byte("</_>"), []byte("</grp>"), -1)
-
- s := &opencv_storage{}
- err = xml.Unmarshal(buf, s)
- if err != nil {
- return
- }
- return buildCascade(s)
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser_test.go
deleted file mode 100644
index 343390499..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/opencv_parser_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
- "os"
- "reflect"
- "testing"
-)
-
-var (
- classifier0 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(0, 0, 3, 4), Weight: -1},
- Feature{Rect: image.Rect(3, 4, 5, 6), Weight: 3.1},
- },
- Threshold: 0.03,
- Left: 0.01,
- Right: 0.8,
- }
- classifier1 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(3, 7, 17, 11), Weight: -3.2},
- Feature{Rect: image.Rect(3, 9, 17, 11), Weight: 2.},
- },
- Threshold: 0.11,
- Left: 0.03,
- Right: 0.83,
- }
- classifier2 = Classifier{
- Feature: []Feature{
- Feature{Rect: image.Rect(1, 1, 3, 3), Weight: -1.},
- Feature{Rect: image.Rect(3, 3, 5, 5), Weight: 2.5},
- },
- Threshold: 0.07,
- Left: 0.2,
- Right: 0.4,
- }
- cascade = Cascade{
- Stage: []CascadeStage{
- CascadeStage{
- Classifier: []Classifier{classifier0, classifier1},
- Threshold: 0.82,
- },
- CascadeStage{
- Classifier: []Classifier{classifier2},
- Threshold: 0.22,
- },
- },
- Size: image.Pt(20, 20),
- }
-)
-
-func TestParseOpenCV(t *testing.T) {
- file, err := os.Open("../../testdata/opencv.xml")
- if err != nil {
- t.Fatal(err)
- }
- defer file.Close()
-
- cascadeFile, name, err := ParseOpenCV(file)
- if err != nil {
- t.Fatal(err)
- }
- if name != "name_of_cascade" {
- t.Fatalf("name: got %s want name_of_cascade", name)
- }
-
- if !reflect.DeepEqual(cascade, *cascadeFile) {
- t.Errorf("got\n %v want\n %v", *cascadeFile, cascade)
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector.go
deleted file mode 100644
index 1ebd6db59..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
-)
-
-// projector allows projecting from a source Rectangle onto a target Rectangle.
-type projector struct {
- // rx, ry is the scaling factor.
- rx, ry float64
- // dx, dy is the translation factor.
- dx, dy float64
- // r is the clipping region of the target.
- r image.Rectangle
-}
-
-// newProjector creates a Projector with source src and target dst.
-func newProjector(dst image.Rectangle, src image.Rectangle) *projector {
- return &projector{
- rx: float64(dst.Dx()) / float64(src.Dx()),
- ry: float64(dst.Dy()) / float64(src.Dy()),
- dx: float64(dst.Min.X - src.Min.X),
- dy: float64(dst.Min.Y - src.Min.Y),
- r: dst,
- }
-}
-
-// pt projects p from the source rectangle onto the target rectangle.
-func (s *projector) pt(p image.Point) image.Point {
- return image.Point{
- clamp(s.rx*float64(p.X)+s.dx, s.r.Min.X, s.r.Max.X),
- clamp(s.ry*float64(p.Y)+s.dy, s.r.Min.Y, s.r.Max.Y),
- }
-}
-
-// rect projects r from the source rectangle onto the target rectangle.
-func (s *projector) rect(r image.Rectangle) image.Rectangle {
- return image.Rectangle{s.pt(r.Min), s.pt(r.Max)}
-}
-
-// clamp rounds and clamps o to the integer range [x0, x1].
-func clamp(o float64, x0, x1 int) int {
- x := int(o + 0.5)
- if x < x0 {
- return x0
- }
- if x > x1 {
- return x1
- }
- return x
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector_test.go
deleted file mode 100644
index c6d0b0cd5..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/detect/projector_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package detect
-
-import (
- "image"
- "reflect"
- "testing"
-)
-
-type projectorTest struct {
- dst image.Rectangle
- src image.Rectangle
- pdst image.Rectangle
- psrc image.Rectangle
-}
-
-var projectorTests = []projectorTest{
- {
- image.Rect(0, 0, 6, 6),
- image.Rect(0, 0, 2, 2),
- image.Rect(0, 0, 6, 6),
- image.Rect(0, 0, 2, 2),
- },
- {
- image.Rect(0, 0, 6, 6),
- image.Rect(0, 0, 2, 2),
- image.Rect(3, 3, 6, 6),
- image.Rect(1, 1, 2, 2),
- },
- {
- image.Rect(30, 30, 40, 40),
- image.Rect(10, 10, 20, 20),
- image.Rect(32, 33, 34, 37),
- image.Rect(12, 13, 14, 17),
- },
-}
-
-func TestProjector(t *testing.T) {
- for i, tt := range projectorTests {
- pr := newProjector(tt.dst, tt.src)
- res := pr.rect(tt.psrc)
- if !reflect.DeepEqual(res, tt.pdst) {
- t.Errorf("%d: got %v want %v", i, res, tt.pdst)
- }
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/Makefile b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/Makefile
deleted file mode 100644
index 7bfdf22d8..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/Makefile
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright 2011 The Graphics-Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-include $(GOROOT)/src/Make.inc
-
-TARG=code.google.com/p/graphics-go/graphics/graphicstest
-GOFILES=\
- graphicstest.go\
-
-include $(GOROOT)/src/Make.pkg
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/graphicstest.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/graphicstest.go
deleted file mode 100644
index ceb3a974d..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/graphicstest/graphicstest.go
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphicstest
-
-import (
- "bytes"
- "errors"
- "fmt"
- "image"
- "image/color"
- "os"
-)
-
-// LoadImage decodes an image from a file.
-func LoadImage(path string) (img image.Image, err error) {
- file, err := os.Open(path)
- if err != nil {
- return
- }
- defer file.Close()
- img, _, err = image.Decode(file)
- return
-}
-
-func delta(u0, u1 uint32) int {
- d := int(u0) - int(u1)
- if d < 0 {
- return -d
- }
- return d
-}
-
-func withinTolerance(c0, c1 color.Color, tol int) bool {
- r0, g0, b0, a0 := c0.RGBA()
- r1, g1, b1, a1 := c1.RGBA()
- r := delta(r0, r1)
- g := delta(g0, g1)
- b := delta(b0, b1)
- a := delta(a0, a1)
- return r <= tol && g <= tol && b <= tol && a <= tol
-}
-
-// ImageWithinTolerance checks that each pixel varies by no more than tol.
-func ImageWithinTolerance(m0, m1 image.Image, tol int) error {
- b0 := m0.Bounds()
- b1 := m1.Bounds()
- if !b0.Eq(b1) {
- return errors.New(fmt.Sprintf("got bounds %v want %v", b0, b1))
- }
-
- for y := b0.Min.Y; y < b0.Max.Y; y++ {
- for x := b0.Min.X; x < b0.Max.X; x++ {
- c0 := m0.At(x, y)
- c1 := m1.At(x, y)
- if !withinTolerance(c0, c1, tol) {
- e := fmt.Sprintf("got %v want %v at (%d, %d)", c0, c1, x, y)
- return errors.New(e)
- }
- }
- }
- return nil
-}
-
-// SprintBox pretty prints the array as a hexidecimal matrix.
-func SprintBox(box []byte, width, height int) string {
- buf := bytes.NewBuffer(nil)
- i := 0
- for y := 0; y < height; y++ {
- for x := 0; x < width; x++ {
- fmt.Fprintf(buf, " 0x%02x,", box[i])
- i++
- }
- buf.WriteByte('\n')
- }
- return buf.String()
-}
-
-// SprintImageR pretty prints the red channel of src. It looks like SprintBox.
-func SprintImageR(src *image.RGBA) string {
- w, h := src.Rect.Dx(), src.Rect.Dy()
- i := 0
- box := make([]byte, w*h)
- for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {
- for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {
- off := (y-src.Rect.Min.Y)*src.Stride + (x-src.Rect.Min.X)*4
- box[i] = src.Pix[off]
- i++
- }
- }
- return SprintBox(box, w, h)
-}
-
-// MakeRGBA returns an image with R, G, B taken from src.
-func MakeRGBA(src []uint8, width int) *image.RGBA {
- b := image.Rect(0, 0, width, len(src)/width)
- ret := image.NewRGBA(b)
- i := 0
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- ret.SetRGBA(x, y, color.RGBA{
- R: src[i],
- G: src[i],
- B: src[i],
- A: 0xff,
- })
- i++
- }
- }
- return ret
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/Makefile b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/Makefile
deleted file mode 100644
index 4d8f524fb..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2012 The Graphics-Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-include $(GOROOT)/src/Make.inc
-
-TARG=code.google.com/p/graphics-go/graphics/interp
-GOFILES=\
- bilinear.go\
- doc.go\
- interp.go\
-
-include $(GOROOT)/src/Make.pkg
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear.go
deleted file mode 100644
index e18321a15..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear.go
+++ /dev/null
@@ -1,206 +0,0 @@
-// Copyright 2012 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package interp
-
-import (
- "image"
- "image/color"
- "math"
-)
-
-// Bilinear implements bilinear interpolation.
-var Bilinear Interp = bilinear{}
-
-type bilinear struct{}
-
-func (i bilinear) Interp(src image.Image, x, y float64) color.Color {
- if src, ok := src.(*image.RGBA); ok {
- return i.RGBA(src, x, y)
- }
- return bilinearGeneral(src, x, y)
-}
-
-func bilinearGeneral(src image.Image, x, y float64) color.Color {
- p := findLinearSrc(src.Bounds(), x, y)
- var fr, fg, fb, fa float64
- var r, g, b, a uint32
-
- r, g, b, a = src.At(p.low.X, p.low.Y).RGBA()
- fr += float64(r) * p.frac00
- fg += float64(g) * p.frac00
- fb += float64(b) * p.frac00
- fa += float64(a) * p.frac00
-
- r, g, b, a = src.At(p.high.X, p.low.Y).RGBA()
- fr += float64(r) * p.frac01
- fg += float64(g) * p.frac01
- fb += float64(b) * p.frac01
- fa += float64(a) * p.frac01
-
- r, g, b, a = src.At(p.low.X, p.high.Y).RGBA()
- fr += float64(r) * p.frac10
- fg += float64(g) * p.frac10
- fb += float64(b) * p.frac10
- fa += float64(a) * p.frac10
-
- r, g, b, a = src.At(p.high.X, p.high.Y).RGBA()
- fr += float64(r) * p.frac11
- fg += float64(g) * p.frac11
- fb += float64(b) * p.frac11
- fa += float64(a) * p.frac11
-
- var c color.RGBA64
- c.R = uint16(fr + 0.5)
- c.G = uint16(fg + 0.5)
- c.B = uint16(fb + 0.5)
- c.A = uint16(fa + 0.5)
- return c
-}
-
-func (bilinear) RGBA(src *image.RGBA, x, y float64) color.RGBA {
- p := findLinearSrc(src.Bounds(), x, y)
-
- // Array offsets for the surrounding pixels.
- off00 := offRGBA(src, p.low.X, p.low.Y)
- off01 := offRGBA(src, p.high.X, p.low.Y)
- off10 := offRGBA(src, p.low.X, p.high.Y)
- off11 := offRGBA(src, p.high.X, p.high.Y)
-
- var fr, fg, fb, fa float64
-
- fr += float64(src.Pix[off00+0]) * p.frac00
- fg += float64(src.Pix[off00+1]) * p.frac00
- fb += float64(src.Pix[off00+2]) * p.frac00
- fa += float64(src.Pix[off00+3]) * p.frac00
-
- fr += float64(src.Pix[off01+0]) * p.frac01
- fg += float64(src.Pix[off01+1]) * p.frac01
- fb += float64(src.Pix[off01+2]) * p.frac01
- fa += float64(src.Pix[off01+3]) * p.frac01
-
- fr += float64(src.Pix[off10+0]) * p.frac10
- fg += float64(src.Pix[off10+1]) * p.frac10
- fb += float64(src.Pix[off10+2]) * p.frac10
- fa += float64(src.Pix[off10+3]) * p.frac10
-
- fr += float64(src.Pix[off11+0]) * p.frac11
- fg += float64(src.Pix[off11+1]) * p.frac11
- fb += float64(src.Pix[off11+2]) * p.frac11
- fa += float64(src.Pix[off11+3]) * p.frac11
-
- var c color.RGBA
- c.R = uint8(fr + 0.5)
- c.G = uint8(fg + 0.5)
- c.B = uint8(fb + 0.5)
- c.A = uint8(fa + 0.5)
- return c
-}
-
-func (bilinear) Gray(src *image.Gray, x, y float64) color.Gray {
- p := findLinearSrc(src.Bounds(), x, y)
-
- // Array offsets for the surrounding pixels.
- off00 := offGray(src, p.low.X, p.low.Y)
- off01 := offGray(src, p.high.X, p.low.Y)
- off10 := offGray(src, p.low.X, p.high.Y)
- off11 := offGray(src, p.high.X, p.high.Y)
-
- var fc float64
- fc += float64(src.Pix[off00]) * p.frac00
- fc += float64(src.Pix[off01]) * p.frac01
- fc += float64(src.Pix[off10]) * p.frac10
- fc += float64(src.Pix[off11]) * p.frac11
-
- var c color.Gray
- c.Y = uint8(fc + 0.5)
- return c
-}
-
-type bilinearSrc struct {
- // Top-left and bottom-right interpolation sources
- low, high image.Point
- // Fraction of each pixel to take. The 0 suffix indicates
- // top/left, and the 1 suffix indicates bottom/right.
- frac00, frac01, frac10, frac11 float64
-}
-
-func findLinearSrc(b image.Rectangle, sx, sy float64) bilinearSrc {
- maxX := float64(b.Max.X)
- maxY := float64(b.Max.Y)
- minX := float64(b.Min.X)
- minY := float64(b.Min.Y)
- lowX := math.Floor(sx - 0.5)
- lowY := math.Floor(sy - 0.5)
- if lowX < minX {
- lowX = minX
- }
- if lowY < minY {
- lowY = minY
- }
-
- highX := math.Ceil(sx - 0.5)
- highY := math.Ceil(sy - 0.5)
- if highX >= maxX {
- highX = maxX - 1
- }
- if highY >= maxY {
- highY = maxY - 1
- }
-
- // In the variables below, the 0 suffix indicates top/left, and the
- // 1 suffix indicates bottom/right.
-
- // Center of each surrounding pixel.
- x00 := lowX + 0.5
- y00 := lowY + 0.5
- x01 := highX + 0.5
- y01 := lowY + 0.5
- x10 := lowX + 0.5
- y10 := highY + 0.5
- x11 := highX + 0.5
- y11 := highY + 0.5
-
- p := bilinearSrc{
- low: image.Pt(int(lowX), int(lowY)),
- high: image.Pt(int(highX), int(highY)),
- }
-
- // Literally, edge cases. If we are close enough to the edge of
- // the image, curtail the interpolation sources.
- if lowX == highX && lowY == highY {
- p.frac00 = 1.0
- } else if sy-minY <= 0.5 && sx-minX <= 0.5 {
- p.frac00 = 1.0
- } else if maxY-sy <= 0.5 && maxX-sx <= 0.5 {
- p.frac11 = 1.0
- } else if sy-minY <= 0.5 || lowY == highY {
- p.frac00 = x01 - sx
- p.frac01 = sx - x00
- } else if sx-minX <= 0.5 || lowX == highX {
- p.frac00 = y10 - sy
- p.frac10 = sy - y00
- } else if maxY-sy <= 0.5 {
- p.frac10 = x11 - sx
- p.frac11 = sx - x10
- } else if maxX-sx <= 0.5 {
- p.frac01 = y11 - sy
- p.frac11 = sy - y01
- } else {
- p.frac00 = (x01 - sx) * (y10 - sy)
- p.frac01 = (sx - x00) * (y11 - sy)
- p.frac10 = (x11 - sx) * (sy - y00)
- p.frac11 = (sx - x10) * (sy - y01)
- }
-
- return p
-}
-
-// TODO(crawshaw): When we have inlining, consider func (p *RGBA) Off(x, y) int
-func offRGBA(src *image.RGBA, x, y int) int {
- return (y-src.Rect.Min.Y)*src.Stride + (x-src.Rect.Min.X)*4
-}
-func offGray(src *image.Gray, x, y int) int {
- return (y-src.Rect.Min.Y)*src.Stride + (x - src.Rect.Min.X)
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear_test.go
deleted file mode 100644
index 242d70546..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/bilinear_test.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2012 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package interp
-
-import (
- "image"
- "image/color"
- "testing"
-)
-
-type interpTest struct {
- desc string
- src []uint8
- srcWidth int
- x, y float64
- expect uint8
-}
-
-func (p *interpTest) newSrc() *image.RGBA {
- b := image.Rect(0, 0, p.srcWidth, len(p.src)/p.srcWidth)
- src := image.NewRGBA(b)
- i := 0
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- src.SetRGBA(x, y, color.RGBA{
- R: p.src[i],
- G: p.src[i],
- B: p.src[i],
- A: 0xff,
- })
- i++
- }
- }
- return src
-}
-
-var interpTests = []interpTest{
- {
- desc: "center of a single white pixel should match that pixel",
- src: []uint8{0x00},
- srcWidth: 1,
- x: 0.5,
- y: 0.5,
- expect: 0x00,
- },
- {
- desc: "middle of a square is equally weighted",
- src: []uint8{
- 0x00, 0xff,
- 0xff, 0x00,
- },
- srcWidth: 2,
- x: 1.0,
- y: 1.0,
- expect: 0x80,
- },
- {
- desc: "center of a pixel is just that pixel",
- src: []uint8{
- 0x00, 0xff,
- 0xff, 0x00,
- },
- srcWidth: 2,
- x: 1.5,
- y: 0.5,
- expect: 0xff,
- },
- {
- desc: "asymmetry abounds",
- src: []uint8{
- 0xaa, 0x11, 0x55,
- 0xff, 0x95, 0xdd,
- },
- srcWidth: 3,
- x: 2.0,
- y: 1.0,
- expect: 0x76, // (0x11 + 0x55 + 0x95 + 0xdd) / 4
- },
-}
-
-func TestBilinearRGBA(t *testing.T) {
- for _, p := range interpTests {
- src := p.newSrc()
-
- // Fast path.
- c := Bilinear.(RGBA).RGBA(src, p.x, p.y)
- if c.R != c.G || c.R != c.B || c.A != 0xff {
- t.Errorf("expect channels to match, got %v", c)
- continue
- }
- if c.R != p.expect {
- t.Errorf("%s: got 0x%02x want 0x%02x", p.desc, c.R, p.expect)
- continue
- }
-
- // Standard Interp should use the fast path.
- cStd := Bilinear.Interp(src, p.x, p.y)
- if cStd != c {
- t.Errorf("%s: standard mismatch got %v want %v", p.desc, cStd, c)
- continue
- }
-
- // General case should match the fast path.
- cGen := color.RGBAModel.Convert(bilinearGeneral(src, p.x, p.y))
- r0, g0, b0, a0 := c.RGBA()
- r1, g1, b1, a1 := cGen.RGBA()
- if r0 != r1 || g0 != g1 || b0 != b1 || a0 != a1 {
- t.Errorf("%s: general case mismatch got %v want %v", p.desc, c, cGen)
- continue
- }
- }
-}
-
-func TestBilinearSubImage(t *testing.T) {
- b0 := image.Rect(0, 0, 4, 4)
- src0 := image.NewRGBA(b0)
- b1 := image.Rect(1, 1, 3, 3)
- src1 := src0.SubImage(b1).(*image.RGBA)
- src1.Set(1, 1, color.RGBA{0x11, 0, 0, 0xff})
- src1.Set(2, 1, color.RGBA{0x22, 0, 0, 0xff})
- src1.Set(1, 2, color.RGBA{0x33, 0, 0, 0xff})
- src1.Set(2, 2, color.RGBA{0x44, 0, 0, 0xff})
-
- tests := []struct {
- x, y float64
- want uint8
- }{
- {1, 1, 0x11},
- {3, 1, 0x22},
- {1, 3, 0x33},
- {3, 3, 0x44},
- {2, 2, 0x2b},
- }
-
- for _, p := range tests {
- c := Bilinear.(RGBA).RGBA(src1, p.x, p.y)
- if c.R != p.want {
- t.Errorf("(%.0f, %.0f): got 0x%02x want 0x%02x", p.x, p.y, c.R, p.want)
- }
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/doc.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/doc.go
deleted file mode 100644
index b115534cc..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/doc.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2012 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package interp implements image interpolation.
-
-An interpolator provides the Interp interface, which can be used
-to interpolate a pixel:
-
- c := interp.Bilinear.Interp(src, 1.2, 1.8)
-
-To interpolate a large number of RGBA or Gray pixels, an implementation
-may provide a fast-path by implementing the RGBA or Gray interfaces.
-
- i1, ok := i.(interp.RGBA)
- if ok {
- c := i1.RGBA(src, 1.2, 1.8)
- // use c.R, c.G, etc
- return
- }
- c := i.Interp(src, 1.2, 1.8)
- // use generic color.Color
-*/
-package interp
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/interp.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/interp.go
deleted file mode 100644
index 560637d4a..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/interp/interp.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package interp
-
-import (
- "image"
- "image/color"
-)
-
-// Interp interpolates an image's color at fractional co-ordinates.
-type Interp interface {
- // Interp interpolates (x, y).
- Interp(src image.Image, x, y float64) color.Color
-}
-
-// RGBA is a fast-path interpolation implementation for image.RGBA.
-// It is common for an Interp to also implement RGBA.
-type RGBA interface {
- // RGBA interpolates (x, y).
- RGBA(src *image.RGBA, x, y float64) color.RGBA
-}
-
-// Gray is a fast-path interpolation implementation for image.Gray.
-type Gray interface {
- // Gray interpolates (x, y).
- Gray(src *image.Gray, x, y float64) color.Gray
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate.go
deleted file mode 100644
index 62bde1a08..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/interp"
- "errors"
- "image"
- "image/draw"
-)
-
-// RotateOptions are the rotation parameters.
-// Angle is the angle, in radians, to rotate the image clockwise.
-type RotateOptions struct {
- Angle float64
-}
-
-// Rotate produces a rotated version of src, drawn onto dst.
-func Rotate(dst draw.Image, src image.Image, opt *RotateOptions) error {
- if dst == nil {
- return errors.New("graphics: dst is nil")
- }
- if src == nil {
- return errors.New("graphics: src is nil")
- }
-
- angle := 0.0
- if opt != nil {
- angle = opt.Angle
- }
-
- return I.Rotate(angle).TransformCenter(dst, src, interp.Bilinear)
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate_test.go
deleted file mode 100644
index bfc532a0a..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/rotate_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "math"
- "testing"
-
- _ "image/png"
-)
-
-var rotateOneColorTests = []transformOneColorTest{
- {
- "onepixel-onequarter", 1, 1, 1, 1,
- &RotateOptions{math.Pi / 2},
- []uint8{0xff},
- []uint8{0xff},
- },
- {
- "onepixel-partial", 1, 1, 1, 1,
- &RotateOptions{math.Pi * 2.0 / 3.0},
- []uint8{0xff},
- []uint8{0xff},
- },
- {
- "onepixel-complete", 1, 1, 1, 1,
- &RotateOptions{2 * math.Pi},
- []uint8{0xff},
- []uint8{0xff},
- },
- {
- "even-onequarter", 2, 2, 2, 2,
- &RotateOptions{math.Pi / 2.0},
- []uint8{
- 0xff, 0x00,
- 0x00, 0xff,
- },
- []uint8{
- 0x00, 0xff,
- 0xff, 0x00,
- },
- },
- {
- "even-complete", 2, 2, 2, 2,
- &RotateOptions{2.0 * math.Pi},
- []uint8{
- 0xff, 0x00,
- 0x00, 0xff,
- },
- []uint8{
- 0xff, 0x00,
- 0x00, 0xff,
- },
- },
- {
- "line-partial", 3, 3, 3, 3,
- &RotateOptions{math.Pi * 1.0 / 3.0},
- []uint8{
- 0x00, 0x00, 0x00,
- 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x00,
- },
- []uint8{
- 0xa2, 0x80, 0x00,
- 0x22, 0xff, 0x22,
- 0x00, 0x80, 0xa2,
- },
- },
- {
- "line-offset-partial", 3, 3, 3, 3,
- &RotateOptions{math.Pi * 3 / 2},
- []uint8{
- 0x00, 0x00, 0x00,
- 0x00, 0xff, 0xff,
- 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0xff, 0x00,
- 0x00, 0xff, 0x00,
- 0x00, 0x00, 0x00,
- },
- },
- {
- "dot-partial", 4, 4, 4, 4,
- &RotateOptions{math.Pi},
- []uint8{
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0xff, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- },
- []uint8{
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- },
- },
-}
-
-func TestRotateOneColor(t *testing.T) {
- for _, oc := range rotateOneColorTests {
- src := oc.newSrc()
- dst := oc.newDst()
-
- if err := Rotate(dst, src, oc.opt.(*RotateOptions)); err != nil {
- t.Errorf("rotate %s: %v", oc.desc, err)
- continue
- }
- if !checkTransformTest(t, &oc, dst) {
- continue
- }
- }
-}
-
-func TestRotateEmpty(t *testing.T) {
- empty := image.NewRGBA(image.Rect(0, 0, 0, 0))
- if err := Rotate(empty, empty, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestRotateGopherSide(t *testing.T) {
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
-
- srcb := src.Bounds()
- dst := image.NewRGBA(image.Rect(0, 0, srcb.Dy(), srcb.Dx()))
- if err := Rotate(dst, src, &RotateOptions{math.Pi / 2.0}); err != nil {
- t.Fatal(err)
- }
-
- cmp, err := graphicstest.LoadImage("../testdata/gopher-rotate-side.png")
- if err != nil {
- t.Fatal(err)
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0x101)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestRotateGopherPartial(t *testing.T) {
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
-
- srcb := src.Bounds()
- dst := image.NewRGBA(image.Rect(0, 0, srcb.Dx(), srcb.Dy()))
- if err := Rotate(dst, src, &RotateOptions{math.Pi / 3.0}); err != nil {
- t.Fatal(err)
- }
-
- cmp, err := graphicstest.LoadImage("../testdata/gopher-rotate-partial.png")
- if err != nil {
- t.Fatal(err)
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0x101)
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale.go
deleted file mode 100644
index 7a7fe9696..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/interp"
- "errors"
- "image"
- "image/draw"
-)
-
-// Scale produces a scaled version of the image using bilinear interpolation.
-func Scale(dst draw.Image, src image.Image) error {
- if dst == nil {
- return errors.New("graphics: dst is nil")
- }
- if src == nil {
- return errors.New("graphics: src is nil")
- }
-
- b := dst.Bounds()
- srcb := src.Bounds()
- if b.Empty() || srcb.Empty() {
- return nil
- }
- sx := float64(b.Dx()) / float64(srcb.Dx())
- sy := float64(b.Dy()) / float64(srcb.Dy())
- return I.Scale(sx, sy).Transform(dst, src, interp.Bilinear)
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale_test.go
deleted file mode 100644
index 9c2468f11..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/scale_test.go
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "testing"
-
- _ "image/png"
-)
-
-var scaleOneColorTests = []transformOneColorTest{
- {
- "down-half",
- 1, 1,
- 2, 2,
- nil,
- []uint8{
- 0x80, 0x00,
- 0x00, 0x80,
- },
- []uint8{
- 0x40,
- },
- },
- {
- "up-double",
- 4, 4,
- 2, 2,
- nil,
- []uint8{
- 0x80, 0x00,
- 0x00, 0x80,
- },
- []uint8{
- 0x80, 0x60, 0x20, 0x00,
- 0x60, 0x50, 0x30, 0x20,
- 0x20, 0x30, 0x50, 0x60,
- 0x00, 0x20, 0x60, 0x80,
- },
- },
- {
- "up-doublewidth",
- 4, 2,
- 2, 2,
- nil,
- []uint8{
- 0x80, 0x00,
- 0x00, 0x80,
- },
- []uint8{
- 0x80, 0x60, 0x20, 0x00,
- 0x00, 0x20, 0x60, 0x80,
- },
- },
- {
- "up-doubleheight",
- 2, 4,
- 2, 2,
- nil,
- []uint8{
- 0x80, 0x00,
- 0x00, 0x80,
- },
- []uint8{
- 0x80, 0x00,
- 0x60, 0x20,
- 0x20, 0x60,
- 0x00, 0x80,
- },
- },
- {
- "up-partial",
- 3, 3,
- 2, 2,
- nil,
- []uint8{
- 0x80, 0x00,
- 0x00, 0x80,
- },
- []uint8{
- 0x80, 0x40, 0x00,
- 0x40, 0x40, 0x40,
- 0x00, 0x40, 0x80,
- },
- },
-}
-
-func TestScaleOneColor(t *testing.T) {
- for _, oc := range scaleOneColorTests {
- dst := oc.newDst()
- src := oc.newSrc()
- if err := Scale(dst, src); err != nil {
- t.Errorf("scale %s: %v", oc.desc, err)
- continue
- }
-
- if !checkTransformTest(t, &oc, dst) {
- continue
- }
- }
-}
-
-func TestScaleEmpty(t *testing.T) {
- empty := image.NewRGBA(image.Rect(0, 0, 0, 0))
- if err := Scale(empty, empty); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestScaleGopher(t *testing.T) {
- dst := image.NewRGBA(image.Rect(0, 0, 100, 150))
-
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Error(err)
- return
- }
-
- // Down-sample.
- if err := Scale(dst, src); err != nil {
- t.Fatal(err)
- }
- cmp, err := graphicstest.LoadImage("../testdata/gopher-100x150.png")
- if err != nil {
- t.Error(err)
- return
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0)
- if err != nil {
- t.Error(err)
- return
- }
-
- // Up-sample.
- dst = image.NewRGBA(image.Rect(0, 0, 500, 750))
- if err := Scale(dst, src); err != nil {
- t.Fatal(err)
- }
- cmp, err = graphicstest.LoadImage("../testdata/gopher-500x750.png")
- if err != nil {
- t.Error(err)
- return
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0)
- if err != nil {
- t.Error(err)
- return
- }
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/shared_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/shared_test.go
deleted file mode 100644
index e1cd21fb3..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/shared_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "bytes"
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "image/color"
- "testing"
-)
-
-type transformOneColorTest struct {
- desc string
- dstWidth int
- dstHeight int
- srcWidth int
- srcHeight int
- opt interface{}
- src []uint8
- res []uint8
-}
-
-func (oc *transformOneColorTest) newSrc() *image.RGBA {
- b := image.Rect(0, 0, oc.srcWidth, oc.srcHeight)
- src := image.NewRGBA(b)
- i := 0
- for y := b.Min.Y; y < b.Max.Y; y++ {
- for x := b.Min.X; x < b.Max.X; x++ {
- src.SetRGBA(x, y, color.RGBA{
- R: oc.src[i],
- G: oc.src[i],
- B: oc.src[i],
- A: oc.src[i],
- })
- i++
- }
- }
- return src
-}
-
-func (oc *transformOneColorTest) newDst() *image.RGBA {
- return image.NewRGBA(image.Rect(0, 0, oc.dstWidth, oc.dstHeight))
-}
-
-func checkTransformTest(t *testing.T, oc *transformOneColorTest, dst *image.RGBA) bool {
- for ch := 0; ch < 4; ch++ {
- i := 0
- res := make([]byte, len(oc.res))
- for y := 0; y < oc.dstHeight; y++ {
- for x := 0; x < oc.dstWidth; x++ {
- off := (y-dst.Rect.Min.Y)*dst.Stride + (x-dst.Rect.Min.X)*4
- res[i] = dst.Pix[off+ch]
- i++
- }
- }
-
- if !bytes.Equal(res, oc.res) {
- got := graphicstest.SprintBox(res, oc.dstWidth, oc.dstHeight)
- want := graphicstest.SprintBox(oc.res, oc.dstWidth, oc.dstHeight)
- t.Errorf("%s: ch=%d\n got\n%s\n want\n%s", oc.desc, ch, got, want)
- return false
- }
- }
-
- return true
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail.go
deleted file mode 100644
index d3ad7e8f7..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "image"
- "image/draw"
-)
-
-// Thumbnail scales and crops src so it fits in dst.
-func Thumbnail(dst draw.Image, src image.Image) error {
- // Scale down src in the dimension that is closer to dst.
- sb := src.Bounds()
- db := dst.Bounds()
- rx := float64(sb.Dx()) / float64(db.Dx())
- ry := float64(sb.Dy()) / float64(db.Dy())
- var b image.Rectangle
- if rx < ry {
- b = image.Rect(0, 0, db.Dx(), int(float64(sb.Dy())/rx))
- } else {
- b = image.Rect(0, 0, int(float64(sb.Dx())/ry), db.Dy())
- }
-
- buf := image.NewRGBA(b)
- if err := Scale(buf, src); err != nil {
- return err
- }
-
- // Crop.
- // TODO(crawshaw): improve on center-alignment.
- var pt image.Point
- if rx < ry {
- pt.Y = (b.Dy() - db.Dy()) / 2
- } else {
- pt.X = (b.Dx() - db.Dx()) / 2
- }
- draw.Draw(dst, db, buf, pt, draw.Src)
- return nil
-}
diff --git a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail_test.go b/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail_test.go
deleted file mode 100644
index d12659f17..000000000
--- a/Godeps/_workspace/src/code.google.com/p/graphics-go/graphics/thumbnail_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2011 The Graphics-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package graphics
-
-import (
- "code.google.com/p/graphics-go/graphics/graphicstest"
- "image"
- "testing"
-
- _ "image/png"
-)
-
-func TestThumbnailGopher(t *testing.T) {
- dst := image.NewRGBA(image.Rect(0, 0, 80, 80))
-
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
- if err := Thumbnail(dst, src); err != nil {
- t.Fatal(err)
- }
- cmp, err := graphicstest.LoadImage("../testdata/gopher-thumb-80x80.png")
- if err != nil {
- t.Fatal(err)
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0)
- if err != nil {
- t.Error(err)
- }
-}
-
-func TestThumbnailLongGopher(t *testing.T) {
- dst := image.NewRGBA(image.Rect(0, 0, 50, 150))
-
- src, err := graphicstest.LoadImage("../testdata/gopher.png")
- if err != nil {
- t.Fatal(err)
- }
- if err := Thumbnail(dst, src); err != nil {
- t.Fatal(err)
- }
- cmp, err := graphicstest.LoadImage("../testdata/gopher-thumb-50x150.png")
- if err != nil {
- t.Fatal(err)
- }
- err = graphicstest.ImageWithinTolerance(dst, cmp, 0)
- if err != nil {
- t.Error(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/LICENSE b/Godeps/_workspace/src/github.com/disintegration/imaging/LICENSE
new file mode 100644
index 000000000..95ae410c3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2012-2014 Grigory Dryapak
+
+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:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+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. \ No newline at end of file
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/README.md b/Godeps/_workspace/src/github.com/disintegration/imaging/README.md
new file mode 100644
index 000000000..16ac8cf6c
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/README.md
@@ -0,0 +1,160 @@
+# Imaging
+
+Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.).
+This package is based on the standard Go image package and works best along with it.
+
+Image manipulation functions provided by the package take any image type
+that implements `image.Image` interface as an input, and return a new image of
+`*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
+
+## Installation
+
+Imaging requires Go version 1.2 or greater.
+
+ go get -u github.com/disintegration/imaging
+
+## Documentation
+
+http://godoc.org/github.com/disintegration/imaging
+
+## Usage examples
+
+A few usage examples can be found below. See the documentation for the full list of supported functions.
+
+### Image resizing
+```go
+// resize srcImage to size = 128x128px using the Lanczos filter
+dstImage128 := imaging.Resize(srcImage, 128, 128, imaging.Lanczos)
+
+// resize srcImage to width = 800px preserving the aspect ratio
+dstImage800 := imaging.Resize(srcImage, 800, 0, imaging.Lanczos)
+
+// scale down srcImage to fit the 800x600px bounding box
+dstImageFit := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
+
+// resize and crop the srcImage to make a 100x100px thumbnail
+dstImageThumb := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
+```
+
+Imaging supports image resizing using various resampling filters. The most notable ones:
+- `NearestNeighbor` - Fastest resampling filter, no antialiasing.
+- `Box` - Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor.
+- `Linear` - Bilinear filter, smooth and reasonably fast.
+- `MitchellNetravali` - А smooth bicubic filter.
+- `CatmullRom` - A sharp bicubic filter.
+- `Gaussian` - Blurring filter that uses gaussian function, useful for noise removal.
+- `Lanczos` - High-quality resampling filter for photographic images yielding sharp results, but it's slower than cubic filters.
+
+The full list of supported filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine. Custom filters can be created using ResampleFilter struct.
+
+**Resampling filters comparison**
+
+Original image. Will be resized from 512x512px to 128x128px.
+
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_512.png)
+
+Filter | Resize result
+---|---
+`imaging.NearestNeighbor` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_nearest.png)
+`imaging.Box` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_box.png)
+`imaging.Linear` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_linear.png)
+`imaging.MitchellNetravali` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_mitchell.png)
+`imaging.CatmullRom` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_catrom.png)
+`imaging.Gaussian` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_gaussian.png)
+`imaging.Lanczos` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_lanczos.png)
+
+### Gaussian Blur
+```go
+dstImage := imaging.Blur(srcImage, 0.5)
+```
+
+Sigma parameter allows to control the strength of the blurring effect.
+
+Original image | Sigma = 0.5 | Sigma = 1.5
+---|---|---
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_128.png) | ![dstImage](http://disintegration.github.io/imaging/out_blur_0.5.png) | ![dstImage](http://disintegration.github.io/imaging/out_blur_1.5.png)
+
+### Sharpening
+```go
+dstImage := imaging.Sharpen(srcImage, 0.5)
+```
+
+Uses gaussian function internally. Sigma parameter allows to control the strength of the sharpening effect.
+
+Original image | Sigma = 0.5 | Sigma = 1.5
+---|---|---
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_128.png) | ![dstImage](http://disintegration.github.io/imaging/out_sharpen_0.5.png) | ![dstImage](http://disintegration.github.io/imaging/out_sharpen_1.5.png)
+
+### Gamma correction
+```go
+dstImage := imaging.AdjustGamma(srcImage, 0.75)
+```
+
+Original image | Gamma = 0.75 | Gamma = 1.25
+---|---|---
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_128.png) | ![dstImage](http://disintegration.github.io/imaging/out_gamma_0.75.png) | ![dstImage](http://disintegration.github.io/imaging/out_gamma_1.25.png)
+
+### Contrast adjustment
+```go
+dstImage := imaging.AdjustContrast(srcImage, 20)
+```
+
+Original image | Contrast = 20 | Contrast = -20
+---|---|---
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_128.png) | ![dstImage](http://disintegration.github.io/imaging/out_contrast_p20.png) | ![dstImage](http://disintegration.github.io/imaging/out_contrast_m20.png)
+
+### Brightness adjustment
+```go
+dstImage := imaging.AdjustBrightness(srcImage, 20)
+```
+
+Original image | Brightness = 20 | Brightness = -20
+---|---|---
+![srcImage](http://disintegration.github.io/imaging/in_lena_bw_128.png) | ![dstImage](http://disintegration.github.io/imaging/out_brightness_p20.png) | ![dstImage](http://disintegration.github.io/imaging/out_brightness_m20.png)
+
+
+### Complete code example
+Here is the code example that loads several images, makes thumbnails of them
+and combines them together side-by-side.
+
+```go
+package main
+
+import (
+ "image"
+ "image/color"
+
+ "github.com/disintegration/imaging"
+)
+
+func main() {
+
+ // input files
+ files := []string{"01.jpg", "02.jpg", "03.jpg"}
+
+ // load images and make 100x100 thumbnails of them
+ var thumbnails []image.Image
+ for _, file := range files {
+ img, err := imaging.Open(file)
+ if err != nil {
+ panic(err)
+ }
+ thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)
+ thumbnails = append(thumbnails, thumb)
+ }
+
+ // create a new blank image
+ dst := imaging.New(100*len(thumbnails), 100, color.NRGBA{0, 0, 0, 0})
+
+ // paste thumbnails into the new image side by side
+ for i, thumb := range thumbnails {
+ dst = imaging.Paste(dst, thumb, image.Pt(i*100, 0))
+ }
+
+ // save the combined image to file
+ err := imaging.Save(dst, "dst.jpg")
+ if err != nil {
+ panic(err)
+ }
+}
+```
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/adjust.go b/Godeps/_workspace/src/github.com/disintegration/imaging/adjust.go
new file mode 100644
index 000000000..9b1b83a4f
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/adjust.go
@@ -0,0 +1,200 @@
+package imaging
+
+import (
+ "image"
+ "image/color"
+ "math"
+)
+
+// AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
+//
+// Example:
+//
+// dstImage = imaging.AdjustFunc(
+// srcImage,
+// func(c color.NRGBA) color.NRGBA {
+// // shift the red channel by 16
+// r := int(c.R) + 16
+// if r > 255 {
+// r = 255
+// }
+// return color.NRGBA{uint8(r), c.G, c.B, c.A}
+// }
+// )
+//
+func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA {
+ src := toNRGBA(img)
+ width := src.Bounds().Max.X
+ height := src.Bounds().Max.Y
+ dst := image.NewNRGBA(image.Rect(0, 0, width, height))
+
+ parallel(height, func(partStart, partEnd int) {
+ for y := partStart; y < partEnd; y++ {
+ for x := 0; x < width; x++ {
+ i := y*src.Stride + x*4
+ j := y*dst.Stride + x*4
+
+ r := src.Pix[i+0]
+ g := src.Pix[i+1]
+ b := src.Pix[i+2]
+ a := src.Pix[i+3]
+
+ c := fn(color.NRGBA{r, g, b, a})
+
+ dst.Pix[j+0] = c.R
+ dst.Pix[j+1] = c.G
+ dst.Pix[j+2] = c.B
+ dst.Pix[j+3] = c.A
+ }
+ }
+ })
+
+ return dst
+}
+
+// AdjustGamma performs a gamma correction on the image and returns the adjusted image.
+// Gamma parameter must be positive. Gamma = 1.0 gives the original image.
+// Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
+//
+// Example:
+//
+// dstImage = imaging.AdjustGamma(srcImage, 0.7)
+//
+func AdjustGamma(img image.Image, gamma float64) *image.NRGBA {
+ e := 1.0 / math.Max(gamma, 0.0001)
+ lut := make([]uint8, 256)
+
+ for i := 0; i < 256; i++ {
+ lut[i] = clamp(math.Pow(float64(i)/255.0, e) * 255.0)
+ }
+
+ fn := func(c color.NRGBA) color.NRGBA {
+ return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
+ }
+
+ return AdjustFunc(img, fn)
+}
+
+func sigmoid(a, b, x float64) float64 {
+ return 1 / (1 + math.Exp(b*(a-x)))
+}
+
+// AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
+// It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
+// The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5.
+// The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10).
+// If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
+//
+// Examples:
+//
+// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // increase the contrast
+// dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // decrease the contrast
+//
+func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA {
+ if factor == 0 {
+ return Clone(img)
+ }
+
+ lut := make([]uint8, 256)
+ a := math.Min(math.Max(midpoint, 0.0), 1.0)
+ b := math.Abs(factor)
+ sig0 := sigmoid(a, b, 0)
+ sig1 := sigmoid(a, b, 1)
+ e := 1.0e-6
+
+ if factor > 0 {
+ for i := 0; i < 256; i++ {
+ x := float64(i) / 255.0
+ sigX := sigmoid(a, b, x)
+ f := (sigX - sig0) / (sig1 - sig0)
+ lut[i] = clamp(f * 255.0)
+ }
+ } else {
+ for i := 0; i < 256; i++ {
+ x := float64(i) / 255.0
+ arg := math.Min(math.Max((sig1-sig0)*x+sig0, e), 1.0-e)
+ f := a - math.Log(1.0/arg-1.0)/b
+ lut[i] = clamp(f * 255.0)
+ }
+ }
+
+ fn := func(c color.NRGBA) color.NRGBA {
+ return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
+ }
+
+ return AdjustFunc(img, fn)
+}
+
+// AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
+// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
+// The percentage = -100 gives solid grey image.
+//
+// Examples:
+//
+// dstImage = imaging.AdjustContrast(srcImage, -10) // decrease image contrast by 10%
+// dstImage = imaging.AdjustContrast(srcImage, 20) // increase image contrast by 20%
+//
+func AdjustContrast(img image.Image, percentage float64) *image.NRGBA {
+ percentage = math.Min(math.Max(percentage, -100.0), 100.0)
+ lut := make([]uint8, 256)
+
+ v := (100.0 + percentage) / 100.0
+ for i := 0; i < 256; i++ {
+ if 0 <= v && v <= 1 {
+ lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*v) * 255.0)
+ } else if 1 < v && v < 2 {
+ lut[i] = clamp((0.5 + (float64(i)/255.0-0.5)*(1/(2.0-v))) * 255.0)
+ } else {
+ lut[i] = uint8(float64(i)/255.0+0.5) * 255
+ }
+ }
+
+ fn := func(c color.NRGBA) color.NRGBA {
+ return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
+ }
+
+ return AdjustFunc(img, fn)
+}
+
+// AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
+// The percentage must be in range (-100, 100). The percentage = 0 gives the original image.
+// The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
+//
+// Examples:
+//
+// dstImage = imaging.AdjustBrightness(srcImage, -15) // decrease image brightness by 15%
+// dstImage = imaging.AdjustBrightness(srcImage, 10) // increase image brightness by 10%
+//
+func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA {
+ percentage = math.Min(math.Max(percentage, -100.0), 100.0)
+ lut := make([]uint8, 256)
+
+ shift := 255.0 * percentage / 100.0
+ for i := 0; i < 256; i++ {
+ lut[i] = clamp(float64(i) + shift)
+ }
+
+ fn := func(c color.NRGBA) color.NRGBA {
+ return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
+ }
+
+ return AdjustFunc(img, fn)
+}
+
+// Grayscale produces grayscale version of the image.
+func Grayscale(img image.Image) *image.NRGBA {
+ fn := func(c color.NRGBA) color.NRGBA {
+ f := 0.299*float64(c.R) + 0.587*float64(c.G) + 0.114*float64(c.B)
+ y := uint8(f + 0.5)
+ return color.NRGBA{y, y, y, c.A}
+ }
+ return AdjustFunc(img, fn)
+}
+
+// Invert produces inverted (negated) version of the image.
+func Invert(img image.Image) *image.NRGBA {
+ fn := func(c color.NRGBA) color.NRGBA {
+ return color.NRGBA{255 - c.R, 255 - c.G, 255 - c.B, c.A}
+ }
+ return AdjustFunc(img, fn)
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/effects.go b/Godeps/_workspace/src/github.com/disintegration/imaging/effects.go
new file mode 100644
index 000000000..fe92e10a2
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/effects.go
@@ -0,0 +1,187 @@
+package imaging
+
+import (
+ "image"
+ "math"
+)
+
+func gaussianBlurKernel(x, sigma float64) float64 {
+ return math.Exp(-(x*x)/(2*sigma*sigma)) / (sigma * math.Sqrt(2*math.Pi))
+}
+
+// Blur produces a blurred version of the image using a Gaussian function.
+// Sigma parameter must be positive and indicates how much the image will be blurred.
+//
+// Usage example:
+//
+// dstImage := imaging.Blur(srcImage, 3.5)
+//
+func Blur(img image.Image, sigma float64) *image.NRGBA {
+ if sigma <= 0 {
+ // sigma parameter must be positive!
+ return Clone(img)
+ }
+
+ src := toNRGBA(img)
+ radius := int(math.Ceil(sigma * 3.0))
+ kernel := make([]float64, radius+1)
+
+ for i := 0; i <= radius; i++ {
+ kernel[i] = gaussianBlurKernel(float64(i), sigma)
+ }
+
+ var dst *image.NRGBA
+ dst = blurHorizontal(src, kernel)
+ dst = blurVertical(dst, kernel)
+
+ return dst
+}
+
+func blurHorizontal(src *image.NRGBA, kernel []float64) *image.NRGBA {
+ radius := len(kernel) - 1
+ width := src.Bounds().Max.X
+ height := src.Bounds().Max.Y
+
+ dst := image.NewNRGBA(image.Rect(0, 0, width, height))
+
+ parallel(width, func(partStart, partEnd int) {
+ for x := partStart; x < partEnd; x++ {
+ start := x - radius
+ if start < 0 {
+ start = 0
+ }
+
+ end := x + radius
+ if end > width-1 {
+ end = width - 1
+ }
+
+ weightSum := 0.0
+ for ix := start; ix <= end; ix++ {
+ weightSum += kernel[absint(x-ix)]
+ }
+
+ for y := 0; y < height; y++ {
+
+ r, g, b, a := 0.0, 0.0, 0.0, 0.0
+ for ix := start; ix <= end; ix++ {
+ weight := kernel[absint(x-ix)]
+ i := y*src.Stride + ix*4
+ r += float64(src.Pix[i+0]) * weight
+ g += float64(src.Pix[i+1]) * weight
+ b += float64(src.Pix[i+2]) * weight
+ a += float64(src.Pix[i+3]) * weight
+ }
+
+ r = math.Min(math.Max(r/weightSum, 0.0), 255.0)
+ g = math.Min(math.Max(g/weightSum, 0.0), 255.0)
+ b = math.Min(math.Max(b/weightSum, 0.0), 255.0)
+ a = math.Min(math.Max(a/weightSum, 0.0), 255.0)
+
+ j := y*dst.Stride + x*4
+ dst.Pix[j+0] = uint8(r + 0.5)
+ dst.Pix[j+1] = uint8(g + 0.5)
+ dst.Pix[j+2] = uint8(b + 0.5)
+ dst.Pix[j+3] = uint8(a + 0.5)
+
+ }
+ }
+ })
+
+ return dst
+}
+
+func blurVertical(src *image.NRGBA, kernel []float64) *image.NRGBA {
+ radius := len(kernel) - 1
+ width := src.Bounds().Max.X
+ height := src.Bounds().Max.Y
+
+ dst := image.NewNRGBA(image.Rect(0, 0, width, height))
+
+ parallel(height, func(partStart, partEnd int) {
+ for y := partStart; y < partEnd; y++ {
+ start := y - radius
+ if start < 0 {
+ start = 0
+ }
+
+ end := y + radius
+ if end > height-1 {
+ end = height - 1
+ }
+
+ weightSum := 0.0
+ for iy := start; iy <= end; iy++ {
+ weightSum += kernel[absint(y-iy)]
+ }
+
+ for x := 0; x < width; x++ {
+
+ r, g, b, a := 0.0, 0.0, 0.0, 0.0
+ for iy := start; iy <= end; iy++ {
+ weight := kernel[absint(y-iy)]
+ i := iy*src.Stride + x*4
+ r += float64(src.Pix[i+0]) * weight
+ g += float64(src.Pix[i+1]) * weight
+ b += float64(src.Pix[i+2]) * weight
+ a += float64(src.Pix[i+3]) * weight
+ }
+
+ r = math.Min(math.Max(r/weightSum, 0.0), 255.0)
+ g = math.Min(math.Max(g/weightSum, 0.0), 255.0)
+ b = math.Min(math.Max(b/weightSum, 0.0), 255.0)
+ a = math.Min(math.Max(a/weightSum, 0.0), 255.0)
+
+ j := y*dst.Stride + x*4
+ dst.Pix[j+0] = uint8(r + 0.5)
+ dst.Pix[j+1] = uint8(g + 0.5)
+ dst.Pix[j+2] = uint8(b + 0.5)
+ dst.Pix[j+3] = uint8(a + 0.5)
+
+ }
+ }
+ })
+
+ return dst
+}
+
+// Sharpen produces a sharpened version of the image.
+// Sigma parameter must be positive and indicates how much the image will be sharpened.
+//
+// Usage example:
+//
+// dstImage := imaging.Sharpen(srcImage, 3.5)
+//
+func Sharpen(img image.Image, sigma float64) *image.NRGBA {
+ if sigma <= 0 {
+ // sigma parameter must be positive!
+ return Clone(img)
+ }
+
+ src := toNRGBA(img)
+ blurred := Blur(img, sigma)
+
+ width := src.Bounds().Max.X
+ height := src.Bounds().Max.Y
+ dst := image.NewNRGBA(image.Rect(0, 0, width, height))
+
+ parallel(height, func(partStart, partEnd int) {
+ for y := partStart; y < partEnd; y++ {
+ for x := 0; x < width; x++ {
+ i := y*src.Stride + x*4
+ for j := 0; j < 4; j++ {
+ k := i + j
+ val := int(src.Pix[k]) + (int(src.Pix[k]) - int(blurred.Pix[k]))
+ if val < 0 {
+ val = 0
+ } else if val > 255 {
+ val = 255
+ }
+ dst.Pix[k] = uint8(val)
+ }
+ }
+ }
+ })
+
+ return dst
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go b/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
new file mode 100644
index 000000000..983b64d71
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
@@ -0,0 +1,392 @@
+/*
+Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.).
+This package is based on the standard Go image package and works best along with it.
+
+Image manipulation functions provided by the package take any image type
+that implements `image.Image` interface as an input, and return a new image of
+`*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).
+*/
+package imaging
+
+import (
+ "errors"
+ "image"
+ "image/color"
+ "image/gif"
+ "image/jpeg"
+ "image/png"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "golang.org/x/image/bmp"
+ "golang.org/x/image/tiff"
+)
+
+type Format int
+
+const (
+ JPEG Format = iota
+ PNG
+ GIF
+ TIFF
+ BMP
+)
+
+func (f Format) String() string {
+ switch f {
+ case JPEG:
+ return "JPEG"
+ case PNG:
+ return "PNG"
+ case GIF:
+ return "GIF"
+ case TIFF:
+ return "TIFF"
+ case BMP:
+ return "BMP"
+ default:
+ return "Unsupported"
+ }
+}
+
+var (
+ ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
+)
+
+// Decode reads an image from r.
+func Decode(r io.Reader) (image.Image, error) {
+ img, _, err := image.Decode(r)
+ if err != nil {
+ return nil, err
+ }
+ return toNRGBA(img), nil
+}
+
+// Open loads an image from file
+func Open(filename string) (image.Image, error) {
+ file, err := os.Open(filename)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ img, err := Decode(file)
+ return img, err
+}
+
+// Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
+func Encode(w io.Writer, img image.Image, format Format) error {
+ var err error
+ switch format {
+ case JPEG:
+ var rgba *image.RGBA
+ if nrgba, ok := img.(*image.NRGBA); ok {
+ if nrgba.Opaque() {
+ rgba = &image.RGBA{
+ Pix: nrgba.Pix,
+ Stride: nrgba.Stride,
+ Rect: nrgba.Rect,
+ }
+ }
+ }
+ if rgba != nil {
+ err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: 95})
+ } else {
+ err = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})
+ }
+
+ case PNG:
+ err = png.Encode(w, img)
+ case GIF:
+ err = gif.Encode(w, img, &gif.Options{NumColors: 256})
+ case TIFF:
+ err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
+ case BMP:
+ err = bmp.Encode(w, img)
+ default:
+ err = ErrUnsupportedFormat
+ }
+ return err
+}
+
+// Save saves the image to file with the specified filename.
+// The format is determined from the filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
+func Save(img image.Image, filename string) (err error) {
+ formats := map[string]Format{
+ ".jpg": JPEG,
+ ".jpeg": JPEG,
+ ".png": PNG,
+ ".tif": TIFF,
+ ".tiff": TIFF,
+ ".bmp": BMP,
+ ".gif": GIF,
+ }
+
+ ext := strings.ToLower(filepath.Ext(filename))
+ f, ok := formats[ext]
+ if !ok {
+ return ErrUnsupportedFormat
+ }
+
+ file, err := os.Create(filename)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+
+ return Encode(file, img, f)
+}
+
+// New creates a new image with the specified width and height, and fills it with the specified color.
+func New(width, height int, fillColor color.Color) *image.NRGBA {
+ if width <= 0 || height <= 0 {
+ return &image.NRGBA{}
+ }
+
+ dst := image.NewNRGBA(image.Rect(0, 0, width, height))
+ c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
+
+ if c.R == 0 && c.G == 0 && c.B == 0 && c.A == 0 {
+ return dst
+ }
+
+ cs := []uint8{c.R, c.G, c.B, c.A}
+
+ // fill the first row
+ for x := 0; x < width; x++ {
+ copy(dst.Pix[x*4:(x+1)*4], cs)
+ }
+ // copy the first row to other rows
+ for y := 1; y < height; y++ {
+ copy(dst.Pix[y*dst.Stride:y*dst.Stride+width*4], dst.Pix[0:width*4])
+ }
+
+ return dst
+}
+
+// Clone returns a copy of the given image.
+func Clone(img image.Image) *image.NRGBA {
+ srcBounds := img.Bounds()
+ srcMinX := srcBounds.Min.X
+ srcMinY := srcBounds.Min.Y
+
+ dstBounds := srcBounds.Sub(srcBounds.Min)
+ dstW := dstBounds.Dx()
+ dstH := dstBounds.Dy()
+ dst := image.NewNRGBA(dstBounds)
+
+ switch src := img.(type) {
+
+ case *image.NRGBA:
+ rowSize := srcBounds.Dx() * 4
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ copy(dst.Pix[di:di+rowSize], src.Pix[si:si+rowSize])
+ }
+ })
+
+ case *image.NRGBA64:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ dst.Pix[di+0] = src.Pix[si+0]
+ dst.Pix[di+1] = src.Pix[si+2]
+ dst.Pix[di+2] = src.Pix[si+4]
+ dst.Pix[di+3] = src.Pix[si+6]
+
+ di += 4
+ si += 8
+
+ }
+ }
+ })
+
+ case *image.RGBA:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ a := src.Pix[si+3]
+ dst.Pix[di+3] = a
+ switch a {
+ case 0:
+ dst.Pix[di+0] = 0
+ dst.Pix[di+1] = 0
+ dst.Pix[di+2] = 0
+ case 0xff:
+ dst.Pix[di+0] = src.Pix[si+0]
+ dst.Pix[di+1] = src.Pix[si+1]
+ dst.Pix[di+2] = src.Pix[si+2]
+ default:
+ dst.Pix[di+0] = uint8(uint16(src.Pix[si+0]) * 0xff / uint16(a))
+ dst.Pix[di+1] = uint8(uint16(src.Pix[si+1]) * 0xff / uint16(a))
+ dst.Pix[di+2] = uint8(uint16(src.Pix[si+2]) * 0xff / uint16(a))
+ }
+
+ di += 4
+ si += 4
+
+ }
+ }
+ })
+
+ case *image.RGBA64:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ a := src.Pix[si+6]
+ dst.Pix[di+3] = a
+ switch a {
+ case 0:
+ dst.Pix[di+0] = 0
+ dst.Pix[di+1] = 0
+ dst.Pix[di+2] = 0
+ case 0xff:
+ dst.Pix[di+0] = src.Pix[si+0]
+ dst.Pix[di+1] = src.Pix[si+2]
+ dst.Pix[di+2] = src.Pix[si+4]
+ default:
+ dst.Pix[di+0] = uint8(uint16(src.Pix[si+0]) * 0xff / uint16(a))
+ dst.Pix[di+1] = uint8(uint16(src.Pix[si+2]) * 0xff / uint16(a))
+ dst.Pix[di+2] = uint8(uint16(src.Pix[si+4]) * 0xff / uint16(a))
+ }
+
+ di += 4
+ si += 8
+
+ }
+ }
+ })
+
+ case *image.Gray:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ c := src.Pix[si]
+ dst.Pix[di+0] = c
+ dst.Pix[di+1] = c
+ dst.Pix[di+2] = c
+ dst.Pix[di+3] = 0xff
+
+ di += 4
+ si += 1
+
+ }
+ }
+ })
+
+ case *image.Gray16:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ c := src.Pix[si]
+ dst.Pix[di+0] = c
+ dst.Pix[di+1] = c
+ dst.Pix[di+2] = c
+ dst.Pix[di+3] = 0xff
+
+ di += 4
+ si += 2
+
+ }
+ }
+ })
+
+ case *image.YCbCr:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ srcX := srcMinX + dstX
+ srcY := srcMinY + dstY
+ siy := src.YOffset(srcX, srcY)
+ sic := src.COffset(srcX, srcY)
+ r, g, b := color.YCbCrToRGB(src.Y[siy], src.Cb[sic], src.Cr[sic])
+ dst.Pix[di+0] = r
+ dst.Pix[di+1] = g
+ dst.Pix[di+2] = b
+ dst.Pix[di+3] = 0xff
+
+ di += 4
+
+ }
+ }
+ })
+
+ case *image.Paletted:
+ plen := len(src.Palette)
+ pnew := make([]color.NRGBA, plen)
+ for i := 0; i < plen; i++ {
+ pnew[i] = color.NRGBAModel.Convert(src.Palette[i]).(color.NRGBA)
+ }
+
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ si := src.PixOffset(srcMinX, srcMinY+dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ c := pnew[src.Pix[si]]
+ dst.Pix[di+0] = c.R
+ dst.Pix[di+1] = c.G
+ dst.Pix[di+2] = c.B
+ dst.Pix[di+3] = c.A
+
+ di += 4
+ si += 1
+
+ }
+ }
+ })
+
+ default:
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ di := dst.PixOffset(0, dstY)
+ for dstX := 0; dstX < dstW; dstX++ {
+
+ c := color.NRGBAModel.Convert(img.At(srcMinX+dstX, srcMinY+dstY)).(color.NRGBA)
+ dst.Pix[di+0] = c.R
+ dst.Pix[di+1] = c.G
+ dst.Pix[di+2] = c.B
+ dst.Pix[di+3] = c.A
+
+ di += 4
+
+ }
+ }
+ })
+
+ }
+
+ return dst
+}
+
+// This function used internally to convert any image type to NRGBA if needed.
+func toNRGBA(img image.Image) *image.NRGBA {
+ srcBounds := img.Bounds()
+ if srcBounds.Min.X == 0 && srcBounds.Min.Y == 0 {
+ if src0, ok := img.(*image.NRGBA); ok {
+ return src0
+ }
+ }
+ return Clone(img)
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go b/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
new file mode 100644
index 000000000..d2efd5c83
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
@@ -0,0 +1,564 @@
+package imaging
+
+import (
+ "image"
+ "math"
+)
+
+type iwpair struct {
+ i int
+ w int32
+}
+
+type pweights struct {
+ iwpairs []iwpair
+ wsum int32
+}
+
+func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) []pweights {
+ du := float64(srcSize) / float64(dstSize)
+ scale := du
+ if scale < 1.0 {
+ scale = 1.0
+ }
+ ru := math.Ceil(scale * filter.Support)
+
+ out := make([]pweights, dstSize)
+
+ for v := 0; v < dstSize; v++ {
+ fu := (float64(v)+0.5)*du - 0.5
+
+ startu := int(math.Ceil(fu - ru))
+ if startu < 0 {
+ startu = 0
+ }
+ endu := int(math.Floor(fu + ru))
+ if endu > srcSize-1 {
+ endu = srcSize - 1
+ }
+
+ wsum := int32(0)
+ for u := startu; u <= endu; u++ {
+ w := int32(0xff * filter.Kernel((float64(u)-fu)/scale))
+ if w != 0 {
+ wsum += w
+ out[v].iwpairs = append(out[v].iwpairs, iwpair{u, w})
+ }
+ }
+ out[v].wsum = wsum
+ }
+
+ return out
+}
+
+// Resize resizes the image to the specified width and height using the specified resampling
+// filter and returns the transformed image. If one of width or height is 0, the image aspect
+// ratio is preserved.
+//
+// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
+// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
+//
+// Usage example:
+//
+// dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
+//
+func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
+ dstW, dstH := width, height
+
+ if dstW < 0 || dstH < 0 {
+ return &image.NRGBA{}
+ }
+ if dstW == 0 && dstH == 0 {
+ return &image.NRGBA{}
+ }
+
+ src := toNRGBA(img)
+
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+
+ if srcW <= 0 || srcH <= 0 {
+ return &image.NRGBA{}
+ }
+
+ // if new width or height is 0 then preserve aspect ratio, minimum 1px
+ if dstW == 0 {
+ tmpW := float64(dstH) * float64(srcW) / float64(srcH)
+ dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
+ }
+ if dstH == 0 {
+ tmpH := float64(dstW) * float64(srcH) / float64(srcW)
+ dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
+ }
+
+ var dst *image.NRGBA
+
+ if filter.Support <= 0.0 {
+ // nearest-neighbor special case
+ dst = resizeNearest(src, dstW, dstH)
+
+ } else {
+ // two-pass resize
+ if srcW != dstW {
+ dst = resizeHorizontal(src, dstW, filter)
+ } else {
+ dst = src
+ }
+
+ if srcH != dstH {
+ dst = resizeVertical(dst, dstH, filter)
+ }
+ }
+
+ return dst
+}
+
+func resizeHorizontal(src *image.NRGBA, width int, filter ResampleFilter) *image.NRGBA {
+ srcBounds := src.Bounds()
+ srcW := srcBounds.Max.X
+ srcH := srcBounds.Max.Y
+
+ dstW := width
+ dstH := srcH
+
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ weights := precomputeWeights(dstW, srcW, filter)
+
+ parallel(dstH, func(partStart, partEnd int) {
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ var c [4]int32
+ for _, iw := range weights[dstX].iwpairs {
+ i := dstY*src.Stride + iw.i*4
+ c[0] += int32(src.Pix[i+0]) * iw.w
+ c[1] += int32(src.Pix[i+1]) * iw.w
+ c[2] += int32(src.Pix[i+2]) * iw.w
+ c[3] += int32(src.Pix[i+3]) * iw.w
+ }
+ j := dstY*dst.Stride + dstX*4
+ sum := weights[dstX].wsum
+ dst.Pix[j+0] = clampint32(int32(float32(c[0])/float32(sum) + 0.5))
+ dst.Pix[j+1] = clampint32(int32(float32(c[1])/float32(sum) + 0.5))
+ dst.Pix[j+2] = clampint32(int32(float32(c[2])/float32(sum) + 0.5))
+ dst.Pix[j+3] = clampint32(int32(float32(c[3])/float32(sum) + 0.5))
+ }
+ }
+ })
+
+ return dst
+}
+
+func resizeVertical(src *image.NRGBA, height int, filter ResampleFilter) *image.NRGBA {
+ srcBounds := src.Bounds()
+ srcW := srcBounds.Max.X
+ srcH := srcBounds.Max.Y
+
+ dstW := srcW
+ dstH := height
+
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ weights := precomputeWeights(dstH, srcH, filter)
+
+ parallel(dstW, func(partStart, partEnd int) {
+
+ for dstX := partStart; dstX < partEnd; dstX++ {
+ for dstY := 0; dstY < dstH; dstY++ {
+ var c [4]int32
+ for _, iw := range weights[dstY].iwpairs {
+ i := iw.i*src.Stride + dstX*4
+ c[0] += int32(src.Pix[i+0]) * iw.w
+ c[1] += int32(src.Pix[i+1]) * iw.w
+ c[2] += int32(src.Pix[i+2]) * iw.w
+ c[3] += int32(src.Pix[i+3]) * iw.w
+ }
+ j := dstY*dst.Stride + dstX*4
+ sum := weights[dstY].wsum
+ dst.Pix[j+0] = clampint32(int32(float32(c[0])/float32(sum) + 0.5))
+ dst.Pix[j+1] = clampint32(int32(float32(c[1])/float32(sum) + 0.5))
+ dst.Pix[j+2] = clampint32(int32(float32(c[2])/float32(sum) + 0.5))
+ dst.Pix[j+3] = clampint32(int32(float32(c[3])/float32(sum) + 0.5))
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// fast nearest-neighbor resize, no filtering
+func resizeNearest(src *image.NRGBA, width, height int) *image.NRGBA {
+ dstW, dstH := width, height
+
+ srcBounds := src.Bounds()
+ srcW := srcBounds.Max.X
+ srcH := srcBounds.Max.Y
+
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ dx := float64(srcW) / float64(dstW)
+ dy := float64(srcH) / float64(dstH)
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ fy := (float64(dstY)+0.5)*dy - 0.5
+
+ for dstX := 0; dstX < dstW; dstX++ {
+ fx := (float64(dstX)+0.5)*dx - 0.5
+
+ srcX := int(math.Min(math.Max(math.Floor(fx+0.5), 0.0), float64(srcW)))
+ srcY := int(math.Min(math.Max(math.Floor(fy+0.5), 0.0), float64(srcH)))
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// Fit scales down the image using the specified resample filter to fit the specified
+// maximum width and height and returns the transformed image.
+//
+// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
+// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
+//
+// Usage example:
+//
+// dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
+//
+func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
+ maxW, maxH := width, height
+
+ if maxW <= 0 || maxH <= 0 {
+ return &image.NRGBA{}
+ }
+
+ srcBounds := img.Bounds()
+ srcW := srcBounds.Dx()
+ srcH := srcBounds.Dy()
+
+ if srcW <= 0 || srcH <= 0 {
+ return &image.NRGBA{}
+ }
+
+ if srcW <= maxW && srcH <= maxH {
+ return Clone(img)
+ }
+
+ srcAspectRatio := float64(srcW) / float64(srcH)
+ maxAspectRatio := float64(maxW) / float64(maxH)
+
+ var newW, newH int
+ if srcAspectRatio > maxAspectRatio {
+ newW = maxW
+ newH = int(float64(newW) / srcAspectRatio)
+ } else {
+ newH = maxH
+ newW = int(float64(newH) * srcAspectRatio)
+ }
+
+ return Resize(img, newW, newH, filter)
+}
+
+// Thumbnail scales the image up or down using the specified resample filter, crops it
+// to the specified width and hight and returns the transformed image.
+//
+// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
+// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
+//
+// Usage example:
+//
+// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
+//
+func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
+ thumbW, thumbH := width, height
+
+ if thumbW <= 0 || thumbH <= 0 {
+ return &image.NRGBA{}
+ }
+
+ srcBounds := img.Bounds()
+ srcW := srcBounds.Dx()
+ srcH := srcBounds.Dy()
+
+ if srcW <= 0 || srcH <= 0 {
+ return &image.NRGBA{}
+ }
+
+ srcAspectRatio := float64(srcW) / float64(srcH)
+ thumbAspectRatio := float64(thumbW) / float64(thumbH)
+
+ var tmp image.Image
+ if srcAspectRatio > thumbAspectRatio {
+ tmp = Resize(img, 0, thumbH, filter)
+ } else {
+ tmp = Resize(img, thumbW, 0, filter)
+ }
+
+ return CropCenter(tmp, thumbW, thumbH)
+}
+
+// Resample filter struct. It can be used to make custom filters.
+//
+// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
+// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
+//
+// General filter recommendations:
+//
+// - Lanczos
+// Probably the best resampling filter for photographic images yielding sharp results,
+// but it's slower than cubic filters (see below).
+//
+// - CatmullRom
+// A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.
+//
+// - MitchellNetravali
+// A high quality cubic filter that produces smoother results with less ringing than CatmullRom.
+//
+// - BSpline
+// A good filter if a very smooth output is needed.
+//
+// - Linear
+// Bilinear interpolation filter, produces reasonably good, smooth output. It's faster than cubic filters.
+//
+// - Box
+// Simple and fast resampling filter appropriate for downscaling.
+// When upscaling it's similar to NearestNeighbor.
+//
+// - NearestNeighbor
+// Fastest resample filter, no antialiasing at all. Rarely used.
+//
+type ResampleFilter struct {
+ Support float64
+ Kernel func(float64) float64
+}
+
+// Nearest-neighbor filter, no anti-aliasing.
+var NearestNeighbor ResampleFilter
+
+// Box filter (averaging pixels).
+var Box ResampleFilter
+
+// Linear filter.
+var Linear ResampleFilter
+
+// Hermite cubic spline filter (BC-spline; B=0; C=0).
+var Hermite ResampleFilter
+
+// Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
+var MitchellNetravali ResampleFilter
+
+// Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
+var CatmullRom ResampleFilter
+
+// Cubic B-spline - smooth cubic filter (BC-spline; B=1; C=0).
+var BSpline ResampleFilter
+
+// Gaussian Blurring Filter.
+var Gaussian ResampleFilter
+
+// Bartlett-windowed sinc filter (3 lobes).
+var Bartlett ResampleFilter
+
+// Lanczos filter (3 lobes).
+var Lanczos ResampleFilter
+
+// Hann-windowed sinc filter (3 lobes).
+var Hann ResampleFilter
+
+// Hamming-windowed sinc filter (3 lobes).
+var Hamming ResampleFilter
+
+// Blackman-windowed sinc filter (3 lobes).
+var Blackman ResampleFilter
+
+// Welch-windowed sinc filter (parabolic window, 3 lobes).
+var Welch ResampleFilter
+
+// Cosine-windowed sinc filter (3 lobes).
+var Cosine ResampleFilter
+
+func bcspline(x, b, c float64) float64 {
+ x = math.Abs(x)
+ if x < 1.0 {
+ return ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
+ }
+ if x < 2.0 {
+ return ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
+ }
+ return 0
+}
+
+func sinc(x float64) float64 {
+ if x == 0 {
+ return 1
+ }
+ return math.Sin(math.Pi*x) / (math.Pi * x)
+}
+
+func init() {
+ NearestNeighbor = ResampleFilter{
+ Support: 0.0, // special case - not applying the filter
+ }
+
+ Box = ResampleFilter{
+ Support: 0.5,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x <= 0.5 {
+ return 1.0
+ }
+ return 0
+ },
+ }
+
+ Linear = ResampleFilter{
+ Support: 1.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 1.0 {
+ return 1.0 - x
+ }
+ return 0
+ },
+ }
+
+ Hermite = ResampleFilter{
+ Support: 1.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 1.0 {
+ return bcspline(x, 0.0, 0.0)
+ }
+ return 0
+ },
+ }
+
+ MitchellNetravali = ResampleFilter{
+ Support: 2.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 2.0 {
+ return bcspline(x, 1.0/3.0, 1.0/3.0)
+ }
+ return 0
+ },
+ }
+
+ CatmullRom = ResampleFilter{
+ Support: 2.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 2.0 {
+ return bcspline(x, 0.0, 0.5)
+ }
+ return 0
+ },
+ }
+
+ BSpline = ResampleFilter{
+ Support: 2.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 2.0 {
+ return bcspline(x, 1.0, 0.0)
+ }
+ return 0
+ },
+ }
+
+ Gaussian = ResampleFilter{
+ Support: 2.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 2.0 {
+ return math.Exp(-2 * x * x)
+ }
+ return 0
+ },
+ }
+
+ Bartlett = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * (3.0 - x) / 3.0
+ }
+ return 0
+ },
+ }
+
+ Lanczos = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * sinc(x/3.0)
+ }
+ return 0
+ },
+ }
+
+ Hann = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * (0.5 + 0.5*math.Cos(math.Pi*x/3.0))
+ }
+ return 0
+ },
+ }
+
+ Hamming = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * (0.54 + 0.46*math.Cos(math.Pi*x/3.0))
+ }
+ return 0
+ },
+ }
+
+ Blackman = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * (0.42 - 0.5*math.Cos(math.Pi*x/3.0+math.Pi) + 0.08*math.Cos(2.0*math.Pi*x/3.0))
+ }
+ return 0
+ },
+ }
+
+ Welch = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * (1.0 - (x * x / 9.0))
+ }
+ return 0
+ },
+ }
+
+ Cosine = ResampleFilter{
+ Support: 3.0,
+ Kernel: func(x float64) float64 {
+ x = math.Abs(x)
+ if x < 3.0 {
+ return sinc(x) * math.Cos((math.Pi/2.0)*(x/3.0))
+ }
+ return 0
+ },
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/tools.go b/Godeps/_workspace/src/github.com/disintegration/imaging/tools.go
new file mode 100644
index 000000000..2c39c900a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/tools.go
@@ -0,0 +1,182 @@
+package imaging
+
+import (
+ "image"
+ "math"
+)
+
+// Anchor is the anchor point for image alignment.
+type Anchor int
+
+const (
+ Center Anchor = iota
+ TopLeft
+ Top
+ TopRight
+ Left
+ Right
+ BottomLeft
+ Bottom
+ BottomRight
+)
+
+func anchorPt(b image.Rectangle, w, h int, anchor Anchor) image.Point {
+ var x, y int
+ switch anchor {
+ case TopLeft:
+ x = b.Min.X
+ y = b.Min.Y
+ case Top:
+ x = b.Min.X + (b.Dx()-w)/2
+ y = b.Min.Y
+ case TopRight:
+ x = b.Max.X - w
+ y = b.Min.Y
+ case Left:
+ x = b.Min.X
+ y = b.Min.Y + (b.Dy()-h)/2
+ case Right:
+ x = b.Max.X - w
+ y = b.Min.Y + (b.Dy()-h)/2
+ case BottomLeft:
+ x = b.Min.X
+ y = b.Max.Y - h
+ case Bottom:
+ x = b.Min.X + (b.Dx()-w)/2
+ y = b.Max.Y - h
+ case BottomRight:
+ x = b.Max.X - w
+ y = b.Max.Y - h
+ default:
+ x = b.Min.X + (b.Dx()-w)/2
+ y = b.Min.Y + (b.Dy()-h)/2
+ }
+ return image.Pt(x, y)
+}
+
+// Crop cuts out a rectangular region with the specified bounds
+// from the image and returns the cropped image.
+func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
+ src := toNRGBA(img)
+ srcRect := rect.Sub(img.Bounds().Min)
+ sub := src.SubImage(srcRect)
+ return Clone(sub) // New image Bounds().Min point will be (0, 0)
+}
+
+// CropAnchor cuts out a rectangular region with the specified size
+// from the image using the specified anchor point and returns the cropped image.
+func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA {
+ srcBounds := img.Bounds()
+ pt := anchorPt(srcBounds, width, height, anchor)
+ r := image.Rect(0, 0, width, height).Add(pt)
+ b := srcBounds.Intersect(r)
+ return Crop(img, b)
+}
+
+// CropCenter cuts out a rectangular region with the specified size
+// from the center of the image and returns the cropped image.
+func CropCenter(img image.Image, width, height int) *image.NRGBA {
+ return CropAnchor(img, width, height, Center)
+}
+
+// Paste pastes the img image to the background image at the specified position and returns the combined image.
+func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
+ src := toNRGBA(img)
+ dst := Clone(background) // cloned image bounds start at (0, 0)
+ startPt := pos.Sub(background.Bounds().Min) // so we should translate start point
+ endPt := startPt.Add(src.Bounds().Size())
+ pasteBounds := image.Rectangle{startPt, endPt}
+
+ if dst.Bounds().Overlaps(pasteBounds) {
+ intersectBounds := dst.Bounds().Intersect(pasteBounds)
+
+ rowSize := intersectBounds.Dx() * 4
+ numRows := intersectBounds.Dy()
+
+ srcStartX := intersectBounds.Min.X - pasteBounds.Min.X
+ srcStartY := intersectBounds.Min.Y - pasteBounds.Min.Y
+
+ i0 := dst.PixOffset(intersectBounds.Min.X, intersectBounds.Min.Y)
+ j0 := src.PixOffset(srcStartX, srcStartY)
+
+ di := dst.Stride
+ dj := src.Stride
+
+ for row := 0; row < numRows; row++ {
+ copy(dst.Pix[i0:i0+rowSize], src.Pix[j0:j0+rowSize])
+ i0 += di
+ j0 += dj
+ }
+ }
+
+ return dst
+}
+
+// PasteCenter pastes the img image to the center of the background image and returns the combined image.
+func PasteCenter(background, img image.Image) *image.NRGBA {
+ bgBounds := background.Bounds()
+ bgW := bgBounds.Dx()
+ bgH := bgBounds.Dy()
+ bgMinX := bgBounds.Min.X
+ bgMinY := bgBounds.Min.Y
+
+ centerX := bgMinX + bgW/2
+ centerY := bgMinY + bgH/2
+
+ x0 := centerX - img.Bounds().Dx()/2
+ y0 := centerY - img.Bounds().Dy()/2
+
+ return Paste(background, img, image.Pt(x0, y0))
+}
+
+// Overlay draws the img image over the background image at given position
+// and returns the combined image. Opacity parameter is the opacity of the img
+// image layer, used to compose the images, it must be from 0.0 to 1.0.
+//
+// Usage examples:
+//
+// // draw the sprite over the background at position (50, 50)
+// dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0)
+//
+// // blend two opaque images of the same size
+// dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)
+//
+func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA {
+ opacity = math.Min(math.Max(opacity, 0.0), 1.0) // check: 0.0 <= opacity <= 1.0
+
+ src := toNRGBA(img)
+ dst := Clone(background) // cloned image bounds start at (0, 0)
+ startPt := pos.Sub(background.Bounds().Min) // so we should translate start point
+ endPt := startPt.Add(src.Bounds().Size())
+ pasteBounds := image.Rectangle{startPt, endPt}
+
+ if dst.Bounds().Overlaps(pasteBounds) {
+ intersectBounds := dst.Bounds().Intersect(pasteBounds)
+
+ for y := intersectBounds.Min.Y; y < intersectBounds.Max.Y; y++ {
+ for x := intersectBounds.Min.X; x < intersectBounds.Max.X; x++ {
+ i := y*dst.Stride + x*4
+
+ srcX := x - pasteBounds.Min.X
+ srcY := y - pasteBounds.Min.Y
+ j := srcY*src.Stride + srcX*4
+
+ a1 := float64(dst.Pix[i+3])
+ a2 := float64(src.Pix[j+3])
+
+ coef2 := opacity * a2 / 255.0
+ coef1 := (1 - coef2) * a1 / 255.0
+ coefSum := coef1 + coef2
+ coef1 /= coefSum
+ coef2 /= coefSum
+
+ dst.Pix[i+0] = uint8(float64(dst.Pix[i+0])*coef1 + float64(src.Pix[j+0])*coef2)
+ dst.Pix[i+1] = uint8(float64(dst.Pix[i+1])*coef1 + float64(src.Pix[j+1])*coef2)
+ dst.Pix[i+2] = uint8(float64(dst.Pix[i+2])*coef1 + float64(src.Pix[j+2])*coef2)
+ dst.Pix[i+3] = uint8(math.Min(a1+a2*opacity*(255.0-a1)/255.0, 255.0))
+ }
+ }
+ }
+
+ return dst
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/transform.go b/Godeps/_workspace/src/github.com/disintegration/imaging/transform.go
new file mode 100644
index 000000000..a11601bba
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/transform.go
@@ -0,0 +1,201 @@
+package imaging
+
+import (
+ "image"
+)
+
+// Rotate90 rotates the image 90 degrees counterclockwise and returns the transformed image.
+func Rotate90(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcH
+ dstH := srcW
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstH - dstY - 1
+ srcY := dstX
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// Rotate180 rotates the image 180 degrees counterclockwise and returns the transformed image.
+func Rotate180(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcW
+ dstH := srcH
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstW - dstX - 1
+ srcY := dstH - dstY - 1
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// Rotate270 rotates the image 270 degrees counterclockwise and returns the transformed image.
+func Rotate270(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcH
+ dstH := srcW
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstY
+ srcY := dstW - dstX - 1
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// FlipH flips the image horizontally (from left to right) and returns the transformed image.
+func FlipH(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcW
+ dstH := srcH
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstW - dstX - 1
+ srcY := dstY
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// FlipV flips the image vertically (from top to bottom) and returns the transformed image.
+func FlipV(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcW
+ dstH := srcH
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstX
+ srcY := dstH - dstY - 1
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// Transpose flips the image horizontally and rotates 90 degrees counter-clockwise.
+func Transpose(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcH
+ dstH := srcW
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstY
+ srcY := dstX
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
+
+// Transverse flips the image vertically and rotates 90 degrees counter-clockwise.
+func Transverse(img image.Image) *image.NRGBA {
+ src := toNRGBA(img)
+ srcW := src.Bounds().Max.X
+ srcH := src.Bounds().Max.Y
+ dstW := srcH
+ dstH := srcW
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+
+ parallel(dstH, func(partStart, partEnd int) {
+
+ for dstY := partStart; dstY < partEnd; dstY++ {
+ for dstX := 0; dstX < dstW; dstX++ {
+ srcX := dstH - dstY - 1
+ srcY := dstW - dstX - 1
+
+ srcOff := srcY*src.Stride + srcX*4
+ dstOff := dstY*dst.Stride + dstX*4
+
+ copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
+ }
+ }
+
+ })
+
+ return dst
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/utils.go b/Godeps/_workspace/src/github.com/disintegration/imaging/utils.go
new file mode 100644
index 000000000..8b1ab8adb
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/utils.go
@@ -0,0 +1,77 @@
+package imaging
+
+import (
+ "math"
+ "runtime"
+ "sync"
+ "sync/atomic"
+)
+
+var parallelizationEnabled = true
+
+// if GOMAXPROCS = 1: no goroutines used
+// if GOMAXPROCS > 1: spawn N=GOMAXPROCS workers in separate goroutines
+func parallel(dataSize int, fn func(partStart, partEnd int)) {
+ numGoroutines := 1
+ partSize := dataSize
+
+ if parallelizationEnabled {
+ numProcs := runtime.GOMAXPROCS(0)
+ if numProcs > 1 {
+ numGoroutines = numProcs
+ partSize = dataSize / (numGoroutines * 10)
+ if partSize < 1 {
+ partSize = 1
+ }
+ }
+ }
+
+ if numGoroutines == 1 {
+ fn(0, dataSize)
+ } else {
+ var wg sync.WaitGroup
+ wg.Add(numGoroutines)
+ idx := uint64(0)
+
+ for p := 0; p < numGoroutines; p++ {
+ go func() {
+ defer wg.Done()
+ for {
+ partStart := int(atomic.AddUint64(&idx, uint64(partSize))) - partSize
+ if partStart >= dataSize {
+ break
+ }
+ partEnd := partStart + partSize
+ if partEnd > dataSize {
+ partEnd = dataSize
+ }
+ fn(partStart, partEnd)
+ }
+ }()
+ }
+
+ wg.Wait()
+ }
+}
+
+func absint(i int) int {
+ if i < 0 {
+ return -i
+ }
+ return i
+}
+
+// clamp & round float64 to uint8 (0..255)
+func clamp(v float64) uint8 {
+ return uint8(math.Min(math.Max(v, 0.0), 255.0) + 0.5)
+}
+
+// clamp int32 to uint8 (0..255)
+func clampint32(v int32) uint8 {
+ if v < 0 {
+ return 0
+ } else if v > 255 {
+ return 255
+ }
+ return uint8(v)
+}
diff --git a/Godeps/_workspace/src/github.com/mssola/user_agent/.travis.yml b/Godeps/_workspace/src/github.com/mssola/user_agent/.travis.yml
index 922091263..33c596acb 100644
--- a/Godeps/_workspace/src/github.com/mssola/user_agent/.travis.yml
+++ b/Godeps/_workspace/src/github.com/mssola/user_agent/.travis.yml
@@ -5,6 +5,7 @@ go:
- 1.2
- 1.3
- 1.4
+ - 1.5
- tip
matrix:
allow_failures:
diff --git a/Godeps/_workspace/src/github.com/mssola/user_agent/all_test.go b/Godeps/_workspace/src/github.com/mssola/user_agent/all_test.go
index 6dca19d5c..34ccbb864 100644
--- a/Godeps/_workspace/src/github.com/mssola/user_agent/all_test.go
+++ b/Godeps/_workspace/src/github.com/mssola/user_agent/all_test.go
@@ -40,6 +40,10 @@ var uastrings = []struct {
{"IE11b32Win7b64MDDRJS", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDRJS; rv:11.0) like Gecko"},
{"IE11Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0)"},
+ // Microsoft Edge
+ {"EdgeDesktop", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"},
+ {"EdgeMobile", "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; DEVICE INFO) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10240"},
+
// Gecko
{"FirefoxMac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8"},
{"FirefoxMacLoc", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"},
@@ -129,6 +133,10 @@ var expected = []string{
"Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
"Mozilla:4.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:false",
+ // Microsoft Edge
+ "Mozilla:5.0 Platform:Windows OS:Windows NT 10.0 Browser:Edge-12.10240 Engine:EdgeHTML Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows Phone 10.0 Browser:Edge-12.10240 Engine:EdgeHTML Bot:false Mobile:true",
+
// Gecko
"Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Browser:Firefox-4.0b8 Engine:Gecko-20100101 Bot:false Mobile:false",
"Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:Firefox-3.6.13 Engine:Gecko-20101203 Bot:false Mobile:false",
diff --git a/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go b/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
index 9fb27e5f3..c5612db7b 100644
--- a/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
+++ b/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
@@ -48,13 +48,21 @@ func (p *UserAgent) detectBrowser(sections []section) {
if slen > 2 {
p.browser.Version = sections[2].version
if engine.name == "AppleWebKit" {
- if sections[slen-1].name == "OPR" {
+ switch sections[slen-1].name {
+ case "Edge":
+ p.browser.Name = "Edge"
+ p.browser.Version = sections[slen-1].version
+ p.browser.Engine = "EdgeHTML"
+ p.browser.EngineVersion = ""
+ case "OPR":
p.browser.Name = "Opera"
p.browser.Version = sections[slen-1].version
- } else if sections[2].name == "Chrome" {
- p.browser.Name = "Chrome"
- } else {
- p.browser.Name = "Safari"
+ default:
+ if sections[2].name == "Chrome" {
+ p.browser.Name = "Chrome"
+ } else {
+ p.browser.Name = "Safari"
+ }
}
} else if engine.name == "Gecko" {
name := sections[2].name
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/.travis.yml b/Godeps/_workspace/src/github.com/nfnt/resize/.travis.yml
deleted file mode 100644
index 57bd4a76e..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: go
-
-go:
- - 1.1
- - 1.2
- - 1.3
- - tip
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/LICENSE b/Godeps/_workspace/src/github.com/nfnt/resize/LICENSE
deleted file mode 100644
index 7836cad5f..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/README.md b/Godeps/_workspace/src/github.com/nfnt/resize/README.md
deleted file mode 100644
index 2aefa75c9..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/README.md
+++ /dev/null
@@ -1,149 +0,0 @@
-Resize
-======
-
-Image resizing for the [Go programming language](http://golang.org) with common interpolation methods.
-
-[![Build Status](https://travis-ci.org/nfnt/resize.svg)](https://travis-ci.org/nfnt/resize)
-
-Installation
-------------
-
-```bash
-$ go get github.com/nfnt/resize
-```
-
-It's that easy!
-
-Usage
------
-
-This package needs at least Go 1.1. Import package with
-
-```go
-import "github.com/nfnt/resize"
-```
-
-The resize package provides 2 functions:
-
-* `resize.Resize` creates a scaled image with new dimensions (`width`, `height`) using the interpolation function `interp`.
- If either `width` or `height` is set to 0, it will be set to an aspect ratio preserving value.
-* `resize.Thumbnail` downscales an image preserving its aspect ratio to the maximum dimensions (`maxWidth`, `maxHeight`).
- It will return the original image if original sizes are smaller than the provided dimensions.
-
-```go
-resize.Resize(width, height uint, img image.Image, interp resize.InterpolationFunction) image.Image
-resize.Thumbnail(maxWidth, maxHeight uint, img image.Image, interp resize.InterpolationFunction) image.Image
-```
-
-The provided interpolation functions are (from fast to slow execution time)
-
-- `NearestNeighbor`: [Nearest-neighbor interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation)
-- `Bilinear`: [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation)
-- `Bicubic`: [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation)
-- `MitchellNetravali`: [Mitchell-Netravali interpolation](http://dl.acm.org/citation.cfm?id=378514)
-- `Lanczos2`: [Lanczos resampling](http://en.wikipedia.org/wiki/Lanczos_resampling) with a=2
-- `Lanczos3`: [Lanczos resampling](http://en.wikipedia.org/wiki/Lanczos_resampling) with a=3
-
-Which of these methods gives the best results depends on your use case.
-
-Sample usage:
-
-```go
-package main
-
-import (
- "github.com/nfnt/resize"
- "image/jpeg"
- "log"
- "os"
-)
-
-func main() {
- // open "test.jpg"
- file, err := os.Open("test.jpg")
- if err != nil {
- log.Fatal(err)
- }
-
- // decode jpeg into image.Image
- img, err := jpeg.Decode(file)
- if err != nil {
- log.Fatal(err)
- }
- file.Close()
-
- // resize to width 1000 using Lanczos resampling
- // and preserve aspect ratio
- m := resize.Resize(1000, 0, img, resize.Lanczos3)
-
- out, err := os.Create("test_resized.jpg")
- if err != nil {
- log.Fatal(err)
- }
- defer out.Close()
-
- // write new image to file
- jpeg.Encode(out, m, nil)
-}
-```
-
-Caveats
--------
-
-* Optimized access routines are used for `image.RGBA`, `image.NRGBA`, `image.RGBA64`, `image.NRGBA64`, `image.YCbCr`, `image.Gray`, and `image.Gray16` types. All other image types are accessed in a generic way that will result in slow processing speed.
-* JPEG images are stored in `image.YCbCr`. This image format stores data in a way that will decrease processing speed. A resize may be up to 2 times slower than with `image.RGBA`.
-
-
-Downsizing Samples
--------
-
-Downsizing is not as simple as it might look like. Images have to be filtered before they are scaled down, otherwise aliasing might occur.
-Filtering is highly subjective: Applying too much will blur the whole image, too little will make aliasing become apparent.
-Resize tries to provide sane defaults that should suffice in most cases.
-
-### Artificial sample
-
-Original image
-![Rings](http://nfnt.github.com/img/rings_lg_orig.png)
-
-<table>
-<tr>
-<th><img src="http://nfnt.github.com/img/rings_300_NearestNeighbor.png" /><br>Nearest-Neighbor</th>
-<th><img src="http://nfnt.github.com/img/rings_300_Bilinear.png" /><br>Bilinear</th>
-</tr>
-<tr>
-<th><img src="http://nfnt.github.com/img/rings_300_Bicubic.png" /><br>Bicubic</th>
-<th><img src="http://nfnt.github.com/img/rings_300_MitchellNetravali.png" /><br>Mitchell-Netravali</th>
-</tr>
-<tr>
-<th><img src="http://nfnt.github.com/img/rings_300_Lanczos2.png" /><br>Lanczos2</th>
-<th><img src="http://nfnt.github.com/img/rings_300_Lanczos3.png" /><br>Lanczos3</th>
-</tr>
-</table>
-
-### Real-Life sample
-
-Original image
-![Original](http://nfnt.github.com/img/IMG_3694_720.jpg)
-
-<table>
-<tr>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_NearestNeighbor.png" /><br>Nearest-Neighbor</th>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_Bilinear.png" /><br>Bilinear</th>
-</tr>
-<tr>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_Bicubic.png" /><br>Bicubic</th>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_MitchellNetravali.png" /><br>Mitchell-Netravali</th>
-</tr>
-<tr>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_Lanczos2.png" /><br>Lanczos2</th>
-<th><img src="http://nfnt.github.com/img/IMG_3694_300_Lanczos3.png" /><br>Lanczos3</th>
-</tr>
-</table>
-
-
-License
--------
-
-Copyright (c) 2012 Jan Schlicht <janschlicht@gmail.com>
-Resize is released under a MIT style license.
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/converter.go b/Godeps/_workspace/src/github.com/nfnt/resize/converter.go
deleted file mode 100644
index b3dd06b8d..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/converter.go
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
-Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import "image"
-
-// Keep value in [0,255] range.
-func clampUint8(in int32) uint8 {
- // casting a negative int to an uint will result in an overflown
- // large uint. this behavior will be exploited here and in other functions
- // to achieve a higher performance.
- if uint32(in) < 256 {
- return uint8(in)
- }
- if in > 255 {
- return 255
- }
- return 0
-}
-
-// Keep value in [0,65535] range.
-func clampUint16(in int64) uint16 {
- if uint64(in) < 65536 {
- return uint16(in)
- }
- if in > 65535 {
- return 65535
- }
- return 0
-}
-
-func resizeGeneric(in image.Image, out *image.NRGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]int64
- var sum int64
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case xi < 0:
- xi = 0
- case xi >= maxX:
- xi = maxX
- }
- r, g, b, a := in.At(xi+in.Bounds().Min.X, x+in.Bounds().Min.Y).RGBA()
-
- // reverse alpha-premultiplication.
- if a != 0 {
- r *= 0xffff
- r /= a
- g *= 0xffff
- g /= a
- b *= 0xffff
- b /= a
- }
-
- rgba[0] += int64(coeff) * int64(r)
- rgba[1] += int64(coeff) * int64(g)
- rgba[2] += int64(coeff) * int64(b)
- rgba[3] += int64(coeff) * int64(a)
- sum += int64(coeff)
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := clampUint16(rgba[0] / sum)
- out.Pix[offset+0] = uint8(value >> 8)
- out.Pix[offset+1] = uint8(value)
- value = clampUint16(rgba[1] / sum)
- out.Pix[offset+2] = uint8(value >> 8)
- out.Pix[offset+3] = uint8(value)
- value = clampUint16(rgba[2] / sum)
- out.Pix[offset+4] = uint8(value >> 8)
- out.Pix[offset+5] = uint8(value)
- value = clampUint16(rgba[3] / sum)
- out.Pix[offset+6] = uint8(value >> 8)
- out.Pix[offset+7] = uint8(value)
- }
- }
-}
-
-func resizeRGBA(in *image.RGBA, out *image.NRGBA, scale float64, coeffs []int16, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]int32
- var sum int32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 4
- case xi >= maxX:
- xi = 4 * maxX
- default:
- xi = 0
- }
-
- r := uint32(row[xi+0])
- g := uint32(row[xi+1])
- b := uint32(row[xi+2])
- a := uint32(row[xi+3])
-
- // reverse alpha-premultiplication.
- if a != 0 {
- r *= 0xff
- r /= a
- g *= 0xff
- g /= a
- b *= 0xff
- b /= a
- }
-
- rgba[0] += int32(coeff) * int32(r)
- rgba[1] += int32(coeff) * int32(g)
- rgba[2] += int32(coeff) * int32(b)
- rgba[3] += int32(coeff) * int32(a)
- sum += int32(coeff)
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
- out.Pix[xo+0] = clampUint8(rgba[0] / sum)
- out.Pix[xo+1] = clampUint8(rgba[1] / sum)
- out.Pix[xo+2] = clampUint8(rgba[2] / sum)
- out.Pix[xo+3] = clampUint8(rgba[3] / sum)
- }
- }
-}
-
-func resizeNRGBA(in *image.NRGBA, out *image.NRGBA, scale float64, coeffs []int16, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]int32
- var sum int32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 4
- case xi >= maxX:
- xi = 4 * maxX
- default:
- xi = 0
- }
- rgba[0] += int32(coeff) * int32(row[xi+0])
- rgba[1] += int32(coeff) * int32(row[xi+1])
- rgba[2] += int32(coeff) * int32(row[xi+2])
- rgba[3] += int32(coeff) * int32(row[xi+3])
- sum += int32(coeff)
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
- out.Pix[xo+0] = clampUint8(rgba[0] / sum)
- out.Pix[xo+1] = clampUint8(rgba[1] / sum)
- out.Pix[xo+2] = clampUint8(rgba[2] / sum)
- out.Pix[xo+3] = clampUint8(rgba[3] / sum)
- }
- }
-}
-
-func resizeRGBA64(in *image.RGBA64, out *image.NRGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]int64
- var sum int64
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 8
- case xi >= maxX:
- xi = 8 * maxX
- default:
- xi = 0
- }
-
- r := uint32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
- g := uint32(uint16(row[xi+2])<<8 | uint16(row[xi+3]))
- b := uint32(uint16(row[xi+4])<<8 | uint16(row[xi+5]))
- a := uint32(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
-
- // reverse alpha-premultiplication.
- if a != 0 {
- r *= 0xffff
- r /= a
- g *= 0xffff
- g /= a
- b *= 0xffff
- b /= a
- }
-
- rgba[0] += int64(coeff) * int64(r)
- rgba[1] += int64(coeff) * int64(g)
- rgba[2] += int64(coeff) * int64(b)
- rgba[3] += int64(coeff) * int64(a)
- sum += int64(coeff)
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := clampUint16(rgba[0] / sum)
- out.Pix[xo+0] = uint8(value >> 8)
- out.Pix[xo+1] = uint8(value)
- value = clampUint16(rgba[1] / sum)
- out.Pix[xo+2] = uint8(value >> 8)
- out.Pix[xo+3] = uint8(value)
- value = clampUint16(rgba[2] / sum)
- out.Pix[xo+4] = uint8(value >> 8)
- out.Pix[xo+5] = uint8(value)
- value = clampUint16(rgba[3] / sum)
- out.Pix[xo+6] = uint8(value >> 8)
- out.Pix[xo+7] = uint8(value)
- }
- }
-}
-
-func resizeNRGBA64(in *image.NRGBA64, out *image.NRGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]int64
- var sum int64
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 8
- case xi >= maxX:
- xi = 8 * maxX
- default:
- xi = 0
- }
- rgba[0] += int64(coeff) * int64(uint16(row[xi+0])<<8|uint16(row[xi+1]))
- rgba[1] += int64(coeff) * int64(uint16(row[xi+2])<<8|uint16(row[xi+3]))
- rgba[2] += int64(coeff) * int64(uint16(row[xi+4])<<8|uint16(row[xi+5]))
- rgba[3] += int64(coeff) * int64(uint16(row[xi+6])<<8|uint16(row[xi+7]))
- sum += int64(coeff)
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := clampUint16(rgba[0] / sum)
- out.Pix[xo+0] = uint8(value >> 8)
- out.Pix[xo+1] = uint8(value)
- value = clampUint16(rgba[1] / sum)
- out.Pix[xo+2] = uint8(value >> 8)
- out.Pix[xo+3] = uint8(value)
- value = clampUint16(rgba[2] / sum)
- out.Pix[xo+4] = uint8(value >> 8)
- out.Pix[xo+5] = uint8(value)
- value = clampUint16(rgba[3] / sum)
- out.Pix[xo+6] = uint8(value >> 8)
- out.Pix[xo+7] = uint8(value)
- }
- }
-}
-
-func resizeGray(in *image.Gray, out *image.Gray, scale float64, coeffs []int16, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[(x-newBounds.Min.X)*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var gray int32
- var sum int32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case xi < 0:
- xi = 0
- case xi >= maxX:
- xi = maxX
- }
- gray += int32(coeff) * int32(row[xi])
- sum += int32(coeff)
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x - newBounds.Min.X)
- out.Pix[offset] = clampUint8(gray / sum)
- }
- }
-}
-
-func resizeGray16(in *image.Gray16, out *image.Gray16, scale float64, coeffs []int32, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var gray int64
- var sum int64
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 2
- case xi >= maxX:
- xi = 2 * maxX
- default:
- xi = 0
- }
- gray += int64(coeff) * int64(uint16(row[xi+0])<<8|uint16(row[xi+1]))
- sum += int64(coeff)
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*2
- value := clampUint16(gray / sum)
- out.Pix[offset+0] = uint8(value >> 8)
- out.Pix[offset+1] = uint8(value)
- }
- }
-}
-
-func resizeYCbCr(in *ycc, out *ycc, scale float64, coeffs []int16, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var p [3]int32
- var sum int32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- coeff := coeffs[ci+i]
- if coeff != 0 {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 3
- case xi >= maxX:
- xi = 3 * maxX
- default:
- xi = 0
- }
- p[0] += int32(coeff) * int32(row[xi+0])
- p[1] += int32(coeff) * int32(row[xi+1])
- p[2] += int32(coeff) * int32(row[xi+2])
- sum += int32(coeff)
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*3
- out.Pix[xo+0] = clampUint8(p[0] / sum)
- out.Pix[xo+1] = clampUint8(p[1] / sum)
- out.Pix[xo+2] = clampUint8(p[2] / sum)
- }
- }
-}
-
-func nearestYCbCr(in *ycc, out *ycc, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var p [3]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 3
- case xi >= maxX:
- xi = 3 * maxX
- default:
- xi = 0
- }
- p[0] += float32(row[xi+0])
- p[1] += float32(row[xi+1])
- p[2] += float32(row[xi+2])
- sum++
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*3
- out.Pix[xo+0] = floatToUint8(p[0] / sum)
- out.Pix[xo+1] = floatToUint8(p[1] / sum)
- out.Pix[xo+2] = floatToUint8(p[2] / sum)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/converter_test.go b/Godeps/_workspace/src/github.com/nfnt/resize/converter_test.go
deleted file mode 100644
index 85639efc2..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/converter_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package resize
-
-import (
- "testing"
-)
-
-func Test_ClampUint8(t *testing.T) {
- var testData = []struct {
- in int32
- expected uint8
- }{
- {0, 0},
- {255, 255},
- {128, 128},
- {-2, 0},
- {256, 255},
- }
- for _, test := range testData {
- actual := clampUint8(test.in)
- if actual != test.expected {
- t.Fail()
- }
- }
-}
-
-func Test_ClampUint16(t *testing.T) {
- var testData = []struct {
- in int64
- expected uint16
- }{
- {0, 0},
- {65535, 65535},
- {128, 128},
- {-2, 0},
- {65536, 65535},
- }
- for _, test := range testData {
- actual := clampUint16(test.in)
- if actual != test.expected {
- t.Fail()
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/filters.go b/Godeps/_workspace/src/github.com/nfnt/resize/filters.go
deleted file mode 100644
index 4ce04e389..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/filters.go
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
-Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import (
- "math"
-)
-
-func nearest(in float64) float64 {
- if in >= -0.5 && in < 0.5 {
- return 1
- }
- return 0
-}
-
-func linear(in float64) float64 {
- in = math.Abs(in)
- if in <= 1 {
- return 1 - in
- }
- return 0
-}
-
-func cubic(in float64) float64 {
- in = math.Abs(in)
- if in <= 1 {
- return in*in*(1.5*in-2.5) + 1.0
- }
- if in <= 2 {
- return in*(in*(2.5-0.5*in)-4.0) + 2.0
- }
- return 0
-}
-
-func mitchellnetravali(in float64) float64 {
- in = math.Abs(in)
- if in <= 1 {
- return (7.0*in*in*in - 12.0*in*in + 5.33333333333) * 0.16666666666
- }
- if in <= 2 {
- return (-2.33333333333*in*in*in + 12.0*in*in - 20.0*in + 10.6666666667) * 0.16666666666
- }
- return 0
-}
-
-func sinc(x float64) float64 {
- x = math.Abs(x) * math.Pi
- if x >= 1.220703e-4 {
- return math.Sin(x) / x
- }
- return 1
-}
-
-func lanczos2(in float64) float64 {
- if in > -2 && in < 2 {
- return sinc(in) * sinc(in*0.5)
- }
- return 0
-}
-
-func lanczos3(in float64) float64 {
- if in > -3 && in < 3 {
- return sinc(in) * sinc(in*0.3333333333333333)
- }
- return 0
-}
-
-// range [-256,256]
-func createWeights8(dy, filterLength int, blur, scale float64, kernel func(float64) float64) ([]int16, []int, int) {
- filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
- filterFactor := math.Min(1./(blur*scale), 1)
-
- coeffs := make([]int16, dy*filterLength)
- start := make([]int, dy)
- for y := 0; y < dy; y++ {
- interpX := scale*(float64(y)+0.5) - 0.5
- start[y] = int(interpX) - filterLength/2 + 1
- interpX -= float64(start[y])
- for i := 0; i < filterLength; i++ {
- in := (interpX - float64(i)) * filterFactor
- coeffs[y*filterLength+i] = int16(kernel(in) * 256)
- }
- }
-
- return coeffs, start, filterLength
-}
-
-// range [-65536,65536]
-func createWeights16(dy, filterLength int, blur, scale float64, kernel func(float64) float64) ([]int32, []int, int) {
- filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
- filterFactor := math.Min(1./(blur*scale), 1)
-
- coeffs := make([]int32, dy*filterLength)
- start := make([]int, dy)
- for y := 0; y < dy; y++ {
- interpX := scale*(float64(y)+0.5) - 0.5
- start[y] = int(interpX) - filterLength/2 + 1
- interpX -= float64(start[y])
- for i := 0; i < filterLength; i++ {
- in := (interpX - float64(i)) * filterFactor
- coeffs[y*filterLength+i] = int32(kernel(in) * 65536)
- }
- }
-
- return coeffs, start, filterLength
-}
-
-func createWeightsNearest(dy, filterLength int, blur, scale float64) ([]bool, []int, int) {
- filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
- filterFactor := math.Min(1./(blur*scale), 1)
-
- coeffs := make([]bool, dy*filterLength)
- start := make([]int, dy)
- for y := 0; y < dy; y++ {
- interpX := scale*(float64(y)+0.5) - 0.5
- start[y] = int(interpX) - filterLength/2 + 1
- interpX -= float64(start[y])
- for i := 0; i < filterLength; i++ {
- in := (interpX - float64(i)) * filterFactor
- if in >= -0.5 && in < 0.5 {
- coeffs[y*filterLength+i] = true
- } else {
- coeffs[y*filterLength+i] = false
- }
- }
- }
-
- return coeffs, start, filterLength
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/nearest.go b/Godeps/_workspace/src/github.com/nfnt/resize/nearest.go
deleted file mode 100644
index 888039d85..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/nearest.go
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
-Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import "image"
-
-func floatToUint8(x float32) uint8 {
- // Nearest-neighbor values are always
- // positive no need to check lower-bound.
- if x > 0xfe {
- return 0xff
- }
- return uint8(x)
-}
-
-func floatToUint16(x float32) uint16 {
- if x > 0xfffe {
- return 0xffff
- }
- return uint16(x)
-}
-
-func nearestGeneric(in image.Image, out *image.RGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case xi < 0:
- xi = 0
- case xi >= maxX:
- xi = maxX
- }
- r, g, b, a := in.At(xi+in.Bounds().Min.X, x+in.Bounds().Min.Y).RGBA()
- rgba[0] += float32(r)
- rgba[1] += float32(g)
- rgba[2] += float32(b)
- rgba[3] += float32(a)
- sum++
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := floatToUint16(rgba[0] / sum)
- out.Pix[offset+0] = uint8(value >> 8)
- out.Pix[offset+1] = uint8(value)
- value = floatToUint16(rgba[1] / sum)
- out.Pix[offset+2] = uint8(value >> 8)
- out.Pix[offset+3] = uint8(value)
- value = floatToUint16(rgba[2] / sum)
- out.Pix[offset+4] = uint8(value >> 8)
- out.Pix[offset+5] = uint8(value)
- value = floatToUint16(rgba[3] / sum)
- out.Pix[offset+6] = uint8(value >> 8)
- out.Pix[offset+7] = uint8(value)
- }
- }
-}
-
-func nearestRGBA(in *image.RGBA, out *image.RGBA, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 4
- case xi >= maxX:
- xi = 4 * maxX
- default:
- xi = 0
- }
- rgba[0] += float32(row[xi+0])
- rgba[1] += float32(row[xi+1])
- rgba[2] += float32(row[xi+2])
- rgba[3] += float32(row[xi+3])
- sum++
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
- out.Pix[xo+0] = floatToUint8(rgba[0] / sum)
- out.Pix[xo+1] = floatToUint8(rgba[1] / sum)
- out.Pix[xo+2] = floatToUint8(rgba[2] / sum)
- out.Pix[xo+3] = floatToUint8(rgba[3] / sum)
- }
- }
-}
-
-func nearestNRGBA(in *image.NRGBA, out *image.NRGBA, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 4
- case xi >= maxX:
- xi = 4 * maxX
- default:
- xi = 0
- }
- rgba[0] += float32(row[xi+0])
- rgba[1] += float32(row[xi+1])
- rgba[2] += float32(row[xi+2])
- rgba[3] += float32(row[xi+3])
- sum++
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
- out.Pix[xo+0] = floatToUint8(rgba[0] / sum)
- out.Pix[xo+1] = floatToUint8(rgba[1] / sum)
- out.Pix[xo+2] = floatToUint8(rgba[2] / sum)
- out.Pix[xo+3] = floatToUint8(rgba[3] / sum)
- }
- }
-}
-
-func nearestRGBA64(in *image.RGBA64, out *image.RGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 8
- case xi >= maxX:
- xi = 8 * maxX
- default:
- xi = 0
- }
- rgba[0] += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
- rgba[1] += float32(uint16(row[xi+2])<<8 | uint16(row[xi+3]))
- rgba[2] += float32(uint16(row[xi+4])<<8 | uint16(row[xi+5]))
- rgba[3] += float32(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
- sum++
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := floatToUint16(rgba[0] / sum)
- out.Pix[xo+0] = uint8(value >> 8)
- out.Pix[xo+1] = uint8(value)
- value = floatToUint16(rgba[1] / sum)
- out.Pix[xo+2] = uint8(value >> 8)
- out.Pix[xo+3] = uint8(value)
- value = floatToUint16(rgba[2] / sum)
- out.Pix[xo+4] = uint8(value >> 8)
- out.Pix[xo+5] = uint8(value)
- value = floatToUint16(rgba[3] / sum)
- out.Pix[xo+6] = uint8(value >> 8)
- out.Pix[xo+7] = uint8(value)
- }
- }
-}
-
-func nearestNRGBA64(in *image.NRGBA64, out *image.NRGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var rgba [4]float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 8
- case xi >= maxX:
- xi = 8 * maxX
- default:
- xi = 0
- }
- rgba[0] += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
- rgba[1] += float32(uint16(row[xi+2])<<8 | uint16(row[xi+3]))
- rgba[2] += float32(uint16(row[xi+4])<<8 | uint16(row[xi+5]))
- rgba[3] += float32(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
- sum++
- }
- }
-
- xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
- value := floatToUint16(rgba[0] / sum)
- out.Pix[xo+0] = uint8(value >> 8)
- out.Pix[xo+1] = uint8(value)
- value = floatToUint16(rgba[1] / sum)
- out.Pix[xo+2] = uint8(value >> 8)
- out.Pix[xo+3] = uint8(value)
- value = floatToUint16(rgba[2] / sum)
- out.Pix[xo+4] = uint8(value >> 8)
- out.Pix[xo+5] = uint8(value)
- value = floatToUint16(rgba[3] / sum)
- out.Pix[xo+6] = uint8(value >> 8)
- out.Pix[xo+7] = uint8(value)
- }
- }
-}
-
-func nearestGray(in *image.Gray, out *image.Gray, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var gray float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case xi < 0:
- xi = 0
- case xi >= maxX:
- xi = maxX
- }
- gray += float32(row[xi])
- sum++
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x - newBounds.Min.X)
- out.Pix[offset] = floatToUint8(gray / sum)
- }
- }
-}
-
-func nearestGray16(in *image.Gray16, out *image.Gray16, scale float64, coeffs []bool, offset []int, filterLength int) {
- newBounds := out.Bounds()
- maxX := in.Bounds().Dx() - 1
-
- for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
- row := in.Pix[x*in.Stride:]
- for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
- var gray float32
- var sum float32
- start := offset[y]
- ci := y * filterLength
- for i := 0; i < filterLength; i++ {
- if coeffs[ci+i] {
- xi := start + i
- switch {
- case uint(xi) < uint(maxX):
- xi *= 2
- case xi >= maxX:
- xi = 2 * maxX
- default:
- xi = 0
- }
- gray += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
- sum++
- }
- }
-
- offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*2
- value := floatToUint16(gray / sum)
- out.Pix[offset+0] = uint8(value >> 8)
- out.Pix[offset+1] = uint8(value)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/nearest_test.go b/Godeps/_workspace/src/github.com/nfnt/resize/nearest_test.go
deleted file mode 100644
index d4a76dda5..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/nearest_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import "testing"
-
-func Test_FloatToUint8(t *testing.T) {
- var testData = []struct {
- in float32
- expected uint8
- }{
- {0, 0},
- {255, 255},
- {128, 128},
- {1, 1},
- {256, 255},
- }
- for _, test := range testData {
- actual := floatToUint8(test.in)
- if actual != test.expected {
- t.Fail()
- }
- }
-}
-
-func Test_FloatToUint16(t *testing.T) {
- var testData = []struct {
- in float32
- expected uint16
- }{
- {0, 0},
- {65535, 65535},
- {128, 128},
- {1, 1},
- {65536, 65535},
- }
- for _, test := range testData {
- actual := floatToUint16(test.in)
- if actual != test.expected {
- t.Fail()
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/resize.go b/Godeps/_workspace/src/github.com/nfnt/resize/resize.go
deleted file mode 100644
index c1672432e..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/resize.go
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
-Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-// Package resize implements various image resizing methods.
-//
-// The package works with the Image interface described in the image package.
-// Various interpolation methods are provided and multiple processors may be
-// utilized in the computations.
-//
-// Example:
-// imgResized := resize.Resize(1000, 0, imgOld, resize.MitchellNetravali)
-package resize
-
-import (
- "image"
- "runtime"
- "sync"
-)
-
-// An InterpolationFunction provides the parameters that describe an
-// interpolation kernel. It returns the number of samples to take
-// and the kernel function to use for sampling.
-type InterpolationFunction int
-
-// InterpolationFunction constants
-const (
- // Nearest-neighbor interpolation
- NearestNeighbor InterpolationFunction = iota
- // Bilinear interpolation
- Bilinear
- // Bicubic interpolation (with cubic hermite spline)
- Bicubic
- // Mitchell-Netravali interpolation
- MitchellNetravali
- // Lanczos interpolation (a=2)
- Lanczos2
- // Lanczos interpolation (a=3)
- Lanczos3
-)
-
-// kernal, returns an InterpolationFunctions taps and kernel.
-func (i InterpolationFunction) kernel() (int, func(float64) float64) {
- switch i {
- case Bilinear:
- return 2, linear
- case Bicubic:
- return 4, cubic
- case MitchellNetravali:
- return 4, mitchellnetravali
- case Lanczos2:
- return 4, lanczos2
- case Lanczos3:
- return 6, lanczos3
- default:
- // Default to NearestNeighbor.
- return 2, nearest
- }
-}
-
-// values <1 will sharpen the image
-var blur = 1.0
-
-// Resize scales an image to new width and height using the interpolation function interp.
-// A new image with the given dimensions will be returned.
-// If one of the parameters width or height is set to 0, its size will be calculated so that
-// the aspect ratio is that of the originating image.
-// The resizing algorithm uses channels for parallel computation.
-func Resize(width, height uint, img image.Image, interp InterpolationFunction) image.Image {
- scaleX, scaleY := calcFactors(width, height, float64(img.Bounds().Dx()), float64(img.Bounds().Dy()))
- if width == 0 {
- width = uint(0.7 + float64(img.Bounds().Dx())/scaleX)
- }
- if height == 0 {
- height = uint(0.7 + float64(img.Bounds().Dy())/scaleY)
- }
-
- // Trivial case: return input image
- if int(width) == img.Bounds().Dx() && int(height) == img.Bounds().Dy() {
- return img
- }
-
- if interp == NearestNeighbor {
- return resizeNearest(width, height, scaleX, scaleY, img, interp)
- }
-
- taps, kernel := interp.kernel()
- cpus := runtime.GOMAXPROCS(0)
- wg := sync.WaitGroup{}
-
- // Generic access to image.Image is slow in tight loops.
- // The optimal access has to be determined from the concrete image type.
- switch input := img.(type) {
- case *image.RGBA:
- // 8-bit precision
- temp := image.NewNRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- resizeRGBA(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- resizeNRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.NRGBA:
- // 8-bit precision
- temp := image.NewNRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- resizeNRGBA(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- resizeNRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
-
- case *image.YCbCr:
- // 8-bit precision
- // accessing the YCbCr arrays in a tight loop is slow.
- // converting the image to ycc increases performance by 2x.
- temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio)
- result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444)
-
- coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- in := imageYCbCrToYCC(input)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*ycc)
- go func() {
- defer wg.Done()
- resizeYCbCr(in, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*ycc)
- go func() {
- defer wg.Done()
- resizeYCbCr(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result.YCbCr()
- case *image.RGBA64:
- // 16-bit precision
- temp := image.NewNRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.NRGBA64:
- // 16-bit precision
- temp := image.NewNRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeNRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.Gray:
- // 8-bit precision
- temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewGray(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.Gray)
- go func() {
- defer wg.Done()
- resizeGray(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.Gray)
- go func() {
- defer wg.Done()
- resizeGray(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.Gray16:
- // 16-bit precision
- temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewGray16(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.Gray16)
- go func() {
- defer wg.Done()
- resizeGray16(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.Gray16)
- go func() {
- defer wg.Done()
- resizeGray16(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- default:
- // 16-bit precision
- temp := image.NewNRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width)))
- result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeGeneric(img, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- resizeNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- }
-}
-
-func resizeNearest(width, height uint, scaleX, scaleY float64, img image.Image, interp InterpolationFunction) image.Image {
- taps, _ := interp.kernel()
- cpus := runtime.GOMAXPROCS(0)
- wg := sync.WaitGroup{}
-
- switch input := img.(type) {
- case *image.RGBA:
- // 8-bit precision
- temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.RGBA)
- go func() {
- defer wg.Done()
- nearestRGBA(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.RGBA)
- go func() {
- defer wg.Done()
- nearestRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.NRGBA:
- // 8-bit precision
- temp := image.NewNRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- nearestNRGBA(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA)
- go func() {
- defer wg.Done()
- nearestNRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.YCbCr:
- // 8-bit precision
- // accessing the YCbCr arrays in a tight loop is slow.
- // converting the image to ycc increases performance by 2x.
- temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio)
- result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444)
-
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- in := imageYCbCrToYCC(input)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*ycc)
- go func() {
- defer wg.Done()
- nearestYCbCr(in, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*ycc)
- go func() {
- defer wg.Done()
- nearestYCbCr(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result.YCbCr()
- case *image.RGBA64:
- // 16-bit precision
- temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.RGBA64)
- go func() {
- defer wg.Done()
- nearestRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.RGBA64)
- go func() {
- defer wg.Done()
- nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.NRGBA64:
- // 16-bit precision
- temp := image.NewNRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- nearestNRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.NRGBA64)
- go func() {
- defer wg.Done()
- nearestNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.Gray:
- // 8-bit precision
- temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewGray(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.Gray)
- go func() {
- defer wg.Done()
- nearestGray(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.Gray)
- go func() {
- defer wg.Done()
- nearestGray(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- case *image.Gray16:
- // 16-bit precision
- temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
- result := image.NewGray16(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.Gray16)
- go func() {
- defer wg.Done()
- nearestGray16(input, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.Gray16)
- go func() {
- defer wg.Done()
- nearestGray16(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- default:
- // 16-bit precision
- temp := image.NewRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width)))
- result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
-
- // horizontal filter, results in transposed temporary image
- coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(temp, i, cpus).(*image.RGBA64)
- go func() {
- defer wg.Done()
- nearestGeneric(img, slice, scaleX, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
-
- // horizontal filter on transposed image, result is not transposed
- coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
- wg.Add(cpus)
- for i := 0; i < cpus; i++ {
- slice := makeSlice(result, i, cpus).(*image.RGBA64)
- go func() {
- defer wg.Done()
- nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
- }()
- }
- wg.Wait()
- return result
- }
-
-}
-
-// Calculates scaling factors using old and new image dimensions.
-func calcFactors(width, height uint, oldWidth, oldHeight float64) (scaleX, scaleY float64) {
- if width == 0 {
- if height == 0 {
- scaleX = 1.0
- scaleY = 1.0
- } else {
- scaleY = oldHeight / float64(height)
- scaleX = scaleY
- }
- } else {
- scaleX = oldWidth / float64(width)
- if height == 0 {
- scaleY = scaleX
- } else {
- scaleY = oldHeight / float64(height)
- }
- }
- return
-}
-
-type imageWithSubImage interface {
- image.Image
- SubImage(image.Rectangle) image.Image
-}
-
-func makeSlice(img imageWithSubImage, i, n int) image.Image {
- return img.SubImage(image.Rect(img.Bounds().Min.X, img.Bounds().Min.Y+i*img.Bounds().Dy()/n, img.Bounds().Max.X, img.Bounds().Min.Y+(i+1)*img.Bounds().Dy()/n))
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/resize_test.go b/Godeps/_workspace/src/github.com/nfnt/resize/resize_test.go
deleted file mode 100644
index 6f6911316..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/resize_test.go
+++ /dev/null
@@ -1,314 +0,0 @@
-package resize
-
-import (
- "image"
- "image/color"
- "runtime"
- "testing"
-)
-
-var img = image.NewGray16(image.Rect(0, 0, 3, 3))
-
-func init() {
- runtime.GOMAXPROCS(runtime.NumCPU())
- img.Set(1, 1, color.White)
-}
-
-func Test_Param1(t *testing.T) {
- m := Resize(0, 0, img, NearestNeighbor)
- if m.Bounds() != img.Bounds() {
- t.Fail()
- }
-}
-
-func Test_Param2(t *testing.T) {
- m := Resize(100, 0, img, NearestNeighbor)
- if m.Bounds() != image.Rect(0, 0, 100, 100) {
- t.Fail()
- }
-}
-
-func Test_ZeroImg(t *testing.T) {
- zeroImg := image.NewGray16(image.Rect(0, 0, 0, 0))
-
- m := Resize(0, 0, zeroImg, NearestNeighbor)
- if m.Bounds() != zeroImg.Bounds() {
- t.Fail()
- }
-}
-
-func Test_CorrectResize(t *testing.T) {
- zeroImg := image.NewGray16(image.Rect(0, 0, 256, 256))
-
- m := Resize(60, 0, zeroImg, NearestNeighbor)
- if m.Bounds() != image.Rect(0, 0, 60, 60) {
- t.Fail()
- }
-}
-
-func Test_SameColorWithRGBA(t *testing.T) {
- img := image.NewRGBA(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetRGBA(x, y, color.RGBA{0x80, 0x80, 0x80, 0xFF})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.NRGBA)
- if color.R != 0x80 || color.G != 0x80 || color.B != 0x80 || color.A != 0xFF {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_SameColorWithNRGBA(t *testing.T) {
- img := image.NewNRGBA(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetNRGBA(x, y, color.NRGBA{0x80, 0x80, 0x80, 0xFF})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.NRGBA)
- if color.R != 0x80 || color.G != 0x80 || color.B != 0x80 || color.A != 0xFF {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_SameColorWithRGBA64(t *testing.T) {
- img := image.NewRGBA64(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetRGBA64(x, y, color.RGBA64{0x8000, 0x8000, 0x8000, 0xFFFF})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.NRGBA64)
- if color.R != 0x8000 || color.G != 0x8000 || color.B != 0x8000 || color.A != 0xFFFF {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_SameColorWithNRGBA64(t *testing.T) {
- img := image.NewNRGBA64(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetNRGBA64(x, y, color.NRGBA64{0x8000, 0x8000, 0x8000, 0xFFFF})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.NRGBA64)
- if color.R != 0x8000 || color.G != 0x8000 || color.B != 0x8000 || color.A != 0xFFFF {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_SameColorWithGray(t *testing.T) {
- img := image.NewGray(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetGray(x, y, color.Gray{0x80})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.Gray)
- if color.Y != 0x80 {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_SameColorWithGray16(t *testing.T) {
- img := image.NewGray16(image.Rect(0, 0, 20, 20))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- img.SetGray16(x, y, color.Gray16{0x8000})
- }
- }
- out := Resize(10, 10, img, Lanczos3)
- for y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {
- for x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {
- color := out.At(x, y).(color.Gray16)
- if color.Y != 0x8000 {
- t.Errorf("%+v", color)
- }
- }
- }
-}
-
-func Test_Bounds(t *testing.T) {
- img := image.NewRGBA(image.Rect(20, 10, 200, 99))
- out := Resize(80, 80, img, Lanczos2)
- out.At(0, 0)
-}
-
-func Test_SameSizeReturnsOriginal(t *testing.T) {
- img := image.NewRGBA(image.Rect(0, 0, 10, 10))
- out := Resize(0, 0, img, Lanczos2)
-
- if img != out {
- t.Fail()
- }
-
- out = Resize(10, 10, img, Lanczos2)
-
- if img != out {
- t.Fail()
- }
-}
-
-func Test_PixelCoordinates(t *testing.T) {
- checkers := image.NewGray(image.Rect(0, 0, 4, 4))
- checkers.Pix = []uint8{
- 255, 0, 255, 0,
- 0, 255, 0, 255,
- 255, 0, 255, 0,
- 0, 255, 0, 255,
- }
-
- resized := Resize(12, 12, checkers, NearestNeighbor).(*image.Gray)
-
- if resized.Pix[0] != 255 || resized.Pix[1] != 255 || resized.Pix[2] != 255 {
- t.Fail()
- }
-
- if resized.Pix[3] != 0 || resized.Pix[4] != 0 || resized.Pix[5] != 0 {
- t.Fail()
- }
-}
-
-func Test_ResizeWithPremultipliedAlpha(t *testing.T) {
- img := image.NewRGBA(image.Rect(0, 0, 1, 4))
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- // 0x80 = 0.5 * 0xFF.
- img.SetRGBA(0, y, color.RGBA{0x80, 0x80, 0x80, 0x80})
- }
-
- out := Resize(1, 2, img, MitchellNetravali)
-
- outputColor := out.At(0, 0).(color.NRGBA)
- if outputColor.R != 0xFF {
- t.Fail()
- }
-}
-
-const (
- // Use a small image size for benchmarks. We don't want memory performance
- // to affect the benchmark results.
- benchMaxX = 250
- benchMaxY = 250
-
- // Resize values near the original size require increase the amount of time
- // resize spends converting the image.
- benchWidth = 200
- benchHeight = 200
-)
-
-func benchRGBA(b *testing.B, interp InterpolationFunction) {
- m := image.NewRGBA(image.Rect(0, 0, benchMaxX, benchMaxY))
- // Initialize m's pixels to create a non-uniform image.
- for y := m.Rect.Min.Y; y < m.Rect.Max.Y; y++ {
- for x := m.Rect.Min.X; x < m.Rect.Max.X; x++ {
- i := m.PixOffset(x, y)
- m.Pix[i+0] = uint8(y + 4*x)
- m.Pix[i+1] = uint8(y + 4*x)
- m.Pix[i+2] = uint8(y + 4*x)
- m.Pix[i+3] = uint8(4*y + x)
- }
- }
-
- var out image.Image
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- out = Resize(benchWidth, benchHeight, m, interp)
- }
- out.At(0, 0)
-}
-
-// The names of some interpolation functions are truncated so that the columns
-// of 'go test -bench' line up.
-func Benchmark_Nearest_RGBA(b *testing.B) {
- benchRGBA(b, NearestNeighbor)
-}
-
-func Benchmark_Bilinear_RGBA(b *testing.B) {
- benchRGBA(b, Bilinear)
-}
-
-func Benchmark_Bicubic_RGBA(b *testing.B) {
- benchRGBA(b, Bicubic)
-}
-
-func Benchmark_Mitchell_RGBA(b *testing.B) {
- benchRGBA(b, MitchellNetravali)
-}
-
-func Benchmark_Lanczos2_RGBA(b *testing.B) {
- benchRGBA(b, Lanczos2)
-}
-
-func Benchmark_Lanczos3_RGBA(b *testing.B) {
- benchRGBA(b, Lanczos3)
-}
-
-func benchYCbCr(b *testing.B, interp InterpolationFunction) {
- m := image.NewYCbCr(image.Rect(0, 0, benchMaxX, benchMaxY), image.YCbCrSubsampleRatio422)
- // Initialize m's pixels to create a non-uniform image.
- for y := m.Rect.Min.Y; y < m.Rect.Max.Y; y++ {
- for x := m.Rect.Min.X; x < m.Rect.Max.X; x++ {
- yi := m.YOffset(x, y)
- ci := m.COffset(x, y)
- m.Y[yi] = uint8(16*y + x)
- m.Cb[ci] = uint8(y + 16*x)
- m.Cr[ci] = uint8(y + 16*x)
- }
- }
- var out image.Image
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- out = Resize(benchWidth, benchHeight, m, interp)
- }
- out.At(0, 0)
-}
-
-func Benchmark_Nearest_YCC(b *testing.B) {
- benchYCbCr(b, NearestNeighbor)
-}
-
-func Benchmark_Bilinear_YCC(b *testing.B) {
- benchYCbCr(b, Bilinear)
-}
-
-func Benchmark_Bicubic_YCC(b *testing.B) {
- benchYCbCr(b, Bicubic)
-}
-
-func Benchmark_Mitchell_YCC(b *testing.B) {
- benchYCbCr(b, MitchellNetravali)
-}
-
-func Benchmark_Lanczos2_YCC(b *testing.B) {
- benchYCbCr(b, Lanczos2)
-}
-
-func Benchmark_Lanczos3_YCC(b *testing.B) {
- benchYCbCr(b, Lanczos3)
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail.go b/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail.go
deleted file mode 100644
index 9efc246be..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail.go
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import (
- "image"
-)
-
-// Thumbnail will downscale provided image to max width and height preserving
-// original aspect ratio and using the interpolation function interp.
-// It will return original image, without processing it, if original sizes
-// are already smaller than provided constraints.
-func Thumbnail(maxWidth, maxHeight uint, img image.Image, interp InterpolationFunction) image.Image {
- origBounds := img.Bounds()
- origWidth := uint(origBounds.Dx())
- origHeight := uint(origBounds.Dy())
- newWidth, newHeight := origWidth, origHeight
-
- // Return original image if it have same or smaller size as constraints
- if maxWidth >= origWidth && maxHeight >= origHeight {
- return img
- }
-
- // Preserve aspect ratio
- if origWidth > maxWidth {
- newHeight = uint(origHeight * maxWidth / origWidth)
- if newHeight < 1 {
- newHeight = 1
- }
- newWidth = maxWidth
- }
-
- if newHeight > maxHeight {
- newWidth = uint(newWidth * maxHeight / newHeight)
- if newWidth < 1 {
- newWidth = 1
- }
- newHeight = maxHeight
- }
- return Resize(newWidth, newHeight, img, interp)
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail_test.go b/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail_test.go
deleted file mode 100644
index bd9875b2b..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/thumbnail_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package resize
-
-import (
- "image"
- "runtime"
- "testing"
-)
-
-func init() {
- runtime.GOMAXPROCS(runtime.NumCPU())
-}
-
-var thumbnailTests = []struct {
- origWidth int
- origHeight int
- maxWidth uint
- maxHeight uint
- expectedWidth uint
- expectedHeight uint
-}{
- {5, 5, 10, 10, 5, 5},
- {10, 10, 5, 5, 5, 5},
- {10, 50, 10, 10, 2, 10},
- {50, 10, 10, 10, 10, 2},
- {50, 100, 60, 90, 45, 90},
- {120, 100, 60, 90, 60, 50},
- {200, 250, 200, 150, 120, 150},
-}
-
-func TestThumbnail(t *testing.T) {
- for i, tt := range thumbnailTests {
- img := image.NewGray16(image.Rect(0, 0, tt.origWidth, tt.origHeight))
-
- outImg := Thumbnail(tt.maxWidth, tt.maxHeight, img, NearestNeighbor)
-
- newWidth := uint(outImg.Bounds().Dx())
- newHeight := uint(outImg.Bounds().Dy())
- if newWidth != tt.expectedWidth ||
- newHeight != tt.expectedHeight {
- t.Errorf("%d. Thumbnail(%v, %v, img, NearestNeighbor) => "+
- "width: %v, height: %v, want width: %v, height: %v",
- i, tt.maxWidth, tt.maxHeight,
- newWidth, newHeight, tt.expectedWidth, tt.expectedHeight,
- )
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/ycc.go b/Godeps/_workspace/src/github.com/nfnt/resize/ycc.go
deleted file mode 100644
index 104159955..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/ycc.go
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
-Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import (
- "image"
- "image/color"
-)
-
-// ycc is an in memory YCbCr image. The Y, Cb and Cr samples are held in a
-// single slice to increase resizing performance.
-type ycc struct {
- // Pix holds the image's pixels, in Y, Cb, Cr order. The pixel at
- // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*3].
- Pix []uint8
- // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
- Stride int
- // Rect is the image's bounds.
- Rect image.Rectangle
- // SubsampleRatio is the subsample ratio of the original YCbCr image.
- SubsampleRatio image.YCbCrSubsampleRatio
-}
-
-// PixOffset returns the index of the first element of Pix that corresponds to
-// the pixel at (x, y).
-func (p *ycc) PixOffset(x, y int) int {
- return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*3
-}
-
-func (p *ycc) Bounds() image.Rectangle {
- return p.Rect
-}
-
-func (p *ycc) ColorModel() color.Model {
- return color.YCbCrModel
-}
-
-func (p *ycc) At(x, y int) color.Color {
- if !(image.Point{x, y}.In(p.Rect)) {
- return color.YCbCr{}
- }
- i := p.PixOffset(x, y)
- return color.YCbCr{
- p.Pix[i+0],
- p.Pix[i+1],
- p.Pix[i+2],
- }
-}
-
-func (p *ycc) Opaque() bool {
- return true
-}
-
-// SubImage returns an image representing the portion of the image p visible
-// through r. The returned value shares pixels with the original image.
-func (p *ycc) SubImage(r image.Rectangle) image.Image {
- r = r.Intersect(p.Rect)
- if r.Empty() {
- return &ycc{SubsampleRatio: p.SubsampleRatio}
- }
- i := p.PixOffset(r.Min.X, r.Min.Y)
- return &ycc{
- Pix: p.Pix[i:],
- Stride: p.Stride,
- Rect: r,
- SubsampleRatio: p.SubsampleRatio,
- }
-}
-
-// newYCC returns a new ycc with the given bounds and subsample ratio.
-func newYCC(r image.Rectangle, s image.YCbCrSubsampleRatio) *ycc {
- w, h := r.Dx(), r.Dy()
- buf := make([]uint8, 3*w*h)
- return &ycc{Pix: buf, Stride: 3 * w, Rect: r, SubsampleRatio: s}
-}
-
-// YCbCr converts ycc to a YCbCr image with the same subsample ratio
-// as the YCbCr image that ycc was generated from.
-func (p *ycc) YCbCr() *image.YCbCr {
- ycbcr := image.NewYCbCr(p.Rect, p.SubsampleRatio)
- var off int
-
- switch ycbcr.SubsampleRatio {
- case image.YCbCrSubsampleRatio422:
- for y := ycbcr.Rect.Min.Y; y < ycbcr.Rect.Max.Y; y++ {
- yy := (y - ycbcr.Rect.Min.Y) * ycbcr.YStride
- cy := (y - ycbcr.Rect.Min.Y) * ycbcr.CStride
- for x := ycbcr.Rect.Min.X; x < ycbcr.Rect.Max.X; x++ {
- xx := (x - ycbcr.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx/2
- ycbcr.Y[yi] = p.Pix[off+0]
- ycbcr.Cb[ci] = p.Pix[off+1]
- ycbcr.Cr[ci] = p.Pix[off+2]
- off += 3
- }
- }
- case image.YCbCrSubsampleRatio420:
- for y := ycbcr.Rect.Min.Y; y < ycbcr.Rect.Max.Y; y++ {
- yy := (y - ycbcr.Rect.Min.Y) * ycbcr.YStride
- cy := (y/2 - ycbcr.Rect.Min.Y/2) * ycbcr.CStride
- for x := ycbcr.Rect.Min.X; x < ycbcr.Rect.Max.X; x++ {
- xx := (x - ycbcr.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx/2
- ycbcr.Y[yi] = p.Pix[off+0]
- ycbcr.Cb[ci] = p.Pix[off+1]
- ycbcr.Cr[ci] = p.Pix[off+2]
- off += 3
- }
- }
- case image.YCbCrSubsampleRatio440:
- for y := ycbcr.Rect.Min.Y; y < ycbcr.Rect.Max.Y; y++ {
- yy := (y - ycbcr.Rect.Min.Y) * ycbcr.YStride
- cy := (y/2 - ycbcr.Rect.Min.Y/2) * ycbcr.CStride
- for x := ycbcr.Rect.Min.X; x < ycbcr.Rect.Max.X; x++ {
- xx := (x - ycbcr.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx
- ycbcr.Y[yi] = p.Pix[off+0]
- ycbcr.Cb[ci] = p.Pix[off+1]
- ycbcr.Cr[ci] = p.Pix[off+2]
- off += 3
- }
- }
- default:
- // Default to 4:4:4 subsampling.
- for y := ycbcr.Rect.Min.Y; y < ycbcr.Rect.Max.Y; y++ {
- yy := (y - ycbcr.Rect.Min.Y) * ycbcr.YStride
- cy := (y - ycbcr.Rect.Min.Y) * ycbcr.CStride
- for x := ycbcr.Rect.Min.X; x < ycbcr.Rect.Max.X; x++ {
- xx := (x - ycbcr.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx
- ycbcr.Y[yi] = p.Pix[off+0]
- ycbcr.Cb[ci] = p.Pix[off+1]
- ycbcr.Cr[ci] = p.Pix[off+2]
- off += 3
- }
- }
- }
- return ycbcr
-}
-
-// imageYCbCrToYCC converts a YCbCr image to a ycc image for resizing.
-func imageYCbCrToYCC(in *image.YCbCr) *ycc {
- w, h := in.Rect.Dx(), in.Rect.Dy()
- r := image.Rect(0, 0, w, h)
- buf := make([]uint8, 3*w*h)
- p := ycc{Pix: buf, Stride: 3 * w, Rect: r, SubsampleRatio: in.SubsampleRatio}
- var off int
-
- switch in.SubsampleRatio {
- case image.YCbCrSubsampleRatio422:
- for y := in.Rect.Min.Y; y < in.Rect.Max.Y; y++ {
- yy := (y - in.Rect.Min.Y) * in.YStride
- cy := (y - in.Rect.Min.Y) * in.CStride
- for x := in.Rect.Min.X; x < in.Rect.Max.X; x++ {
- xx := (x - in.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx/2
- p.Pix[off+0] = in.Y[yi]
- p.Pix[off+1] = in.Cb[ci]
- p.Pix[off+2] = in.Cr[ci]
- off += 3
- }
- }
- case image.YCbCrSubsampleRatio420:
- for y := in.Rect.Min.Y; y < in.Rect.Max.Y; y++ {
- yy := (y - in.Rect.Min.Y) * in.YStride
- cy := (y/2 - in.Rect.Min.Y/2) * in.CStride
- for x := in.Rect.Min.X; x < in.Rect.Max.X; x++ {
- xx := (x - in.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx/2
- p.Pix[off+0] = in.Y[yi]
- p.Pix[off+1] = in.Cb[ci]
- p.Pix[off+2] = in.Cr[ci]
- off += 3
- }
- }
- case image.YCbCrSubsampleRatio440:
- for y := in.Rect.Min.Y; y < in.Rect.Max.Y; y++ {
- yy := (y - in.Rect.Min.Y) * in.YStride
- cy := (y/2 - in.Rect.Min.Y/2) * in.CStride
- for x := in.Rect.Min.X; x < in.Rect.Max.X; x++ {
- xx := (x - in.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx
- p.Pix[off+0] = in.Y[yi]
- p.Pix[off+1] = in.Cb[ci]
- p.Pix[off+2] = in.Cr[ci]
- off += 3
- }
- }
- default:
- // Default to 4:4:4 subsampling.
- for y := in.Rect.Min.Y; y < in.Rect.Max.Y; y++ {
- yy := (y - in.Rect.Min.Y) * in.YStride
- cy := (y - in.Rect.Min.Y) * in.CStride
- for x := in.Rect.Min.X; x < in.Rect.Max.X; x++ {
- xx := (x - in.Rect.Min.X)
- yi := yy + xx
- ci := cy + xx
- p.Pix[off+0] = in.Y[yi]
- p.Pix[off+1] = in.Cb[ci]
- p.Pix[off+2] = in.Cr[ci]
- off += 3
- }
- }
- }
- return &p
-}
diff --git a/Godeps/_workspace/src/github.com/nfnt/resize/ycc_test.go b/Godeps/_workspace/src/github.com/nfnt/resize/ycc_test.go
deleted file mode 100644
index 54d53d157..000000000
--- a/Godeps/_workspace/src/github.com/nfnt/resize/ycc_test.go
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
-Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
-
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright notice
-and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-*/
-
-package resize
-
-import (
- "image"
- "image/color"
- "testing"
-)
-
-type Image interface {
- image.Image
- SubImage(image.Rectangle) image.Image
-}
-
-func TestImage(t *testing.T) {
- testImage := []Image{
- newYCC(image.Rect(0, 0, 10, 10), image.YCbCrSubsampleRatio420),
- newYCC(image.Rect(0, 0, 10, 10), image.YCbCrSubsampleRatio422),
- newYCC(image.Rect(0, 0, 10, 10), image.YCbCrSubsampleRatio440),
- newYCC(image.Rect(0, 0, 10, 10), image.YCbCrSubsampleRatio444),
- }
- for _, m := range testImage {
- if !image.Rect(0, 0, 10, 10).Eq(m.Bounds()) {
- t.Errorf("%T: want bounds %v, got %v",
- m, image.Rect(0, 0, 10, 10), m.Bounds())
- continue
- }
- m = m.SubImage(image.Rect(3, 2, 9, 8)).(Image)
- if !image.Rect(3, 2, 9, 8).Eq(m.Bounds()) {
- t.Errorf("%T: sub-image want bounds %v, got %v",
- m, image.Rect(3, 2, 9, 8), m.Bounds())
- continue
- }
- // Test that taking an empty sub-image starting at a corner does not panic.
- m.SubImage(image.Rect(0, 0, 0, 0))
- m.SubImage(image.Rect(10, 0, 10, 0))
- m.SubImage(image.Rect(0, 10, 0, 10))
- m.SubImage(image.Rect(10, 10, 10, 10))
- }
-}
-
-func TestConvertYCbCr(t *testing.T) {
- testImage := []Image{
- image.NewYCbCr(image.Rect(0, 0, 50, 50), image.YCbCrSubsampleRatio420),
- image.NewYCbCr(image.Rect(0, 0, 50, 50), image.YCbCrSubsampleRatio422),
- image.NewYCbCr(image.Rect(0, 0, 50, 50), image.YCbCrSubsampleRatio440),
- image.NewYCbCr(image.Rect(0, 0, 50, 50), image.YCbCrSubsampleRatio444),
- }
-
- for _, img := range testImage {
- m := img.(*image.YCbCr)
- for y := m.Rect.Min.Y; y < m.Rect.Max.Y; y++ {
- for x := m.Rect.Min.X; x < m.Rect.Max.X; x++ {
- yi := m.YOffset(x, y)
- ci := m.COffset(x, y)
- m.Y[yi] = uint8(16*y + x)
- m.Cb[ci] = uint8(y + 16*x)
- m.Cr[ci] = uint8(y + 16*x)
- }
- }
-
- // test conversion from YCbCr to ycc
- yc := imageYCbCrToYCC(m)
- for y := m.Rect.Min.Y; y < m.Rect.Max.Y; y++ {
- for x := m.Rect.Min.X; x < m.Rect.Max.X; x++ {
- ystride := 3 * (m.Rect.Max.X - m.Rect.Min.X)
- xstride := 3
- yi := m.YOffset(x, y)
- ci := m.COffset(x, y)
- si := (y * ystride) + (x * xstride)
- if m.Y[yi] != yc.Pix[si] {
- t.Errorf("Err Y - found: %d expected: %d x: %d y: %d yi: %d si: %d",
- m.Y[yi], yc.Pix[si], x, y, yi, si)
- }
- if m.Cb[ci] != yc.Pix[si+1] {
- t.Errorf("Err Cb - found: %d expected: %d x: %d y: %d ci: %d si: %d",
- m.Cb[ci], yc.Pix[si+1], x, y, ci, si+1)
- }
- if m.Cr[ci] != yc.Pix[si+2] {
- t.Errorf("Err Cr - found: %d expected: %d x: %d y: %d ci: %d si: %d",
- m.Cr[ci], yc.Pix[si+2], x, y, ci, si+2)
- }
- }
- }
-
- // test conversion from ycc back to YCbCr
- ym := yc.YCbCr()
- for y := m.Rect.Min.Y; y < m.Rect.Max.Y; y++ {
- for x := m.Rect.Min.X; x < m.Rect.Max.X; x++ {
- yi := m.YOffset(x, y)
- ci := m.COffset(x, y)
- if m.Y[yi] != ym.Y[yi] {
- t.Errorf("Err Y - found: %d expected: %d x: %d y: %d yi: %d",
- m.Y[yi], ym.Y[yi], x, y, yi)
- }
- if m.Cb[ci] != ym.Cb[ci] {
- t.Errorf("Err Cb - found: %d expected: %d x: %d y: %d ci: %d",
- m.Cb[ci], ym.Cb[ci], x, y, ci)
- }
- if m.Cr[ci] != ym.Cr[ci] {
- t.Errorf("Err Cr - found: %d expected: %d x: %d y: %d ci: %d",
- m.Cr[ci], ym.Cr[ci], x, y, ci)
- }
- }
- }
- }
-}
-
-func TestYCbCr(t *testing.T) {
- rects := []image.Rectangle{
- image.Rect(0, 0, 16, 16),
- image.Rect(1, 0, 16, 16),
- image.Rect(0, 1, 16, 16),
- image.Rect(1, 1, 16, 16),
- image.Rect(1, 1, 15, 16),
- image.Rect(1, 1, 16, 15),
- image.Rect(1, 1, 15, 15),
- image.Rect(2, 3, 14, 15),
- image.Rect(7, 0, 7, 16),
- image.Rect(0, 8, 16, 8),
- image.Rect(0, 0, 10, 11),
- image.Rect(5, 6, 16, 16),
- image.Rect(7, 7, 8, 8),
- image.Rect(7, 8, 8, 9),
- image.Rect(8, 7, 9, 8),
- image.Rect(8, 8, 9, 9),
- image.Rect(7, 7, 17, 17),
- image.Rect(8, 8, 17, 17),
- image.Rect(9, 9, 17, 17),
- image.Rect(10, 10, 17, 17),
- }
- subsampleRatios := []image.YCbCrSubsampleRatio{
- image.YCbCrSubsampleRatio444,
- image.YCbCrSubsampleRatio422,
- image.YCbCrSubsampleRatio420,
- image.YCbCrSubsampleRatio440,
- }
- deltas := []image.Point{
- image.Pt(0, 0),
- image.Pt(1000, 1001),
- image.Pt(5001, -400),
- image.Pt(-701, -801),
- }
- for _, r := range rects {
- for _, subsampleRatio := range subsampleRatios {
- for _, delta := range deltas {
- testYCbCr(t, r, subsampleRatio, delta)
- }
- }
- if testing.Short() {
- break
- }
- }
-}
-
-func testYCbCr(t *testing.T, r image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio, delta image.Point) {
- // Create a YCbCr image m, whose bounds are r translated by (delta.X, delta.Y).
- r1 := r.Add(delta)
- img := image.NewYCbCr(r1, subsampleRatio)
-
- // Initialize img's pixels. For 422 and 420 subsampling, some of the Cb and Cr elements
- // will be set multiple times. That's OK. We just want to avoid a uniform image.
- for y := r1.Min.Y; y < r1.Max.Y; y++ {
- for x := r1.Min.X; x < r1.Max.X; x++ {
- yi := img.YOffset(x, y)
- ci := img.COffset(x, y)
- img.Y[yi] = uint8(16*y + x)
- img.Cb[ci] = uint8(y + 16*x)
- img.Cr[ci] = uint8(y + 16*x)
- }
- }
-
- m := imageYCbCrToYCC(img)
-
- // Make various sub-images of m.
- for y0 := delta.Y + 3; y0 < delta.Y+7; y0++ {
- for y1 := delta.Y + 8; y1 < delta.Y+13; y1++ {
- for x0 := delta.X + 3; x0 < delta.X+7; x0++ {
- for x1 := delta.X + 8; x1 < delta.X+13; x1++ {
- subRect := image.Rect(x0, y0, x1, y1)
- sub := m.SubImage(subRect).(*ycc)
-
- // For each point in the sub-image's bounds, check that m.At(x, y) equals sub.At(x, y).
- for y := sub.Rect.Min.Y; y < sub.Rect.Max.Y; y++ {
- for x := sub.Rect.Min.X; x < sub.Rect.Max.X; x++ {
- color0 := m.At(x, y).(color.YCbCr)
- color1 := sub.At(x, y).(color.YCbCr)
- if color0 != color1 {
- t.Errorf("r=%v, subsampleRatio=%v, delta=%v, x=%d, y=%d, color0=%v, color1=%v",
- r, subsampleRatio, delta, x, y, color0, color1)
- return
- }
- }
- }
- }
- }
- }
- }
-}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/buffer.go b/Godeps/_workspace/src/golang.org/x/image/tiff/buffer.go
new file mode 100644
index 000000000..d1801be48
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/buffer.go
@@ -0,0 +1,69 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package tiff
+
+import "io"
+
+// buffer buffers an io.Reader to satisfy io.ReaderAt.
+type buffer struct {
+ r io.Reader
+ buf []byte
+}
+
+// fill reads data from b.r until the buffer contains at least end bytes.
+func (b *buffer) fill(end int) error {
+ m := len(b.buf)
+ if end > m {
+ if end > cap(b.buf) {
+ newcap := 1024
+ for newcap < end {
+ newcap *= 2
+ }
+ newbuf := make([]byte, end, newcap)
+ copy(newbuf, b.buf)
+ b.buf = newbuf
+ } else {
+ b.buf = b.buf[:end]
+ }
+ if n, err := io.ReadFull(b.r, b.buf[m:end]); err != nil {
+ end = m + n
+ b.buf = b.buf[:end]
+ return err
+ }
+ }
+ return nil
+}
+
+func (b *buffer) ReadAt(p []byte, off int64) (int, error) {
+ o := int(off)
+ end := o + len(p)
+ if int64(end) != off+int64(len(p)) {
+ return 0, io.ErrUnexpectedEOF
+ }
+
+ err := b.fill(end)
+ return copy(p, b.buf[o:end]), err
+}
+
+// Slice returns a slice of the underlying buffer. The slice contains
+// n bytes starting at offset off.
+func (b *buffer) Slice(off, n int) ([]byte, error) {
+ end := off + n
+ if err := b.fill(end); err != nil {
+ return nil, err
+ }
+ return b.buf[off:end], nil
+}
+
+// newReaderAt converts an io.Reader into an io.ReaderAt.
+func newReaderAt(r io.Reader) io.ReaderAt {
+ if ra, ok := r.(io.ReaderAt); ok {
+ return ra
+ }
+ return &buffer{
+ r: r,
+ buf: make([]byte, 0, 1024),
+ }
+}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/compress.go b/Godeps/_workspace/src/golang.org/x/image/tiff/compress.go
new file mode 100644
index 000000000..3f176f00a
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/compress.go
@@ -0,0 +1,58 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package tiff
+
+import (
+ "bufio"
+ "io"
+)
+
+type byteReader interface {
+ io.Reader
+ io.ByteReader
+}
+
+// unpackBits decodes the PackBits-compressed data in src and returns the
+// uncompressed data.
+//
+// The PackBits compression format is described in section 9 (p. 42)
+// of the TIFF spec.
+func unpackBits(r io.Reader) ([]byte, error) {
+ buf := make([]byte, 128)
+ dst := make([]byte, 0, 1024)
+ br, ok := r.(byteReader)
+ if !ok {
+ br = bufio.NewReader(r)
+ }
+
+ for {
+ b, err := br.ReadByte()
+ if err != nil {
+ if err == io.EOF {
+ return dst, nil
+ }
+ return nil, err
+ }
+ code := int(int8(b))
+ switch {
+ case code >= 0:
+ n, err := io.ReadFull(br, buf[:code+1])
+ if err != nil {
+ return nil, err
+ }
+ dst = append(dst, buf[:n]...)
+ case code == -128:
+ // No-op.
+ default:
+ if b, err = br.ReadByte(); err != nil {
+ return nil, err
+ }
+ for j := 0; j < 1-code; j++ {
+ buf[j] = b
+ }
+ dst = append(dst, buf[:1-code]...)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/consts.go b/Godeps/_workspace/src/golang.org/x/image/tiff/consts.go
new file mode 100644
index 000000000..3c51a70be
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/consts.go
@@ -0,0 +1,133 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package tiff
+
+// A tiff image file contains one or more images. The metadata
+// of each image is contained in an Image File Directory (IFD),
+// which contains entries of 12 bytes each and is described
+// on page 14-16 of the specification. An IFD entry consists of
+//
+// - a tag, which describes the signification of the entry,
+// - the data type and length of the entry,
+// - the data itself or a pointer to it if it is more than 4 bytes.
+//
+// The presence of a length means that each IFD is effectively an array.
+
+const (
+ leHeader = "II\x2A\x00" // Header for little-endian files.
+ beHeader = "MM\x00\x2A" // Header for big-endian files.
+
+ ifdLen = 12 // Length of an IFD entry in bytes.
+)
+
+// Data types (p. 14-16 of the spec).
+const (
+ dtByte = 1
+ dtASCII = 2
+ dtShort = 3
+ dtLong = 4
+ dtRational = 5
+)
+
+// The length of one instance of each data type in bytes.
+var lengths = [...]uint32{0, 1, 1, 2, 4, 8}
+
+// Tags (see p. 28-41 of the spec).
+const (
+ tImageWidth = 256
+ tImageLength = 257
+ tBitsPerSample = 258
+ tCompression = 259
+ tPhotometricInterpretation = 262
+
+ tStripOffsets = 273
+ tSamplesPerPixel = 277
+ tRowsPerStrip = 278
+ tStripByteCounts = 279
+
+ tTileWidth = 322
+ tTileLength = 323
+ tTileOffsets = 324
+ tTileByteCounts = 325
+
+ tXResolution = 282
+ tYResolution = 283
+ tResolutionUnit = 296
+
+ tPredictor = 317
+ tColorMap = 320
+ tExtraSamples = 338
+ tSampleFormat = 339
+)
+
+// Compression types (defined in various places in the spec and supplements).
+const (
+ cNone = 1
+ cCCITT = 2
+ cG3 = 3 // Group 3 Fax.
+ cG4 = 4 // Group 4 Fax.
+ cLZW = 5
+ cJPEGOld = 6 // Superseded by cJPEG.
+ cJPEG = 7
+ cDeflate = 8 // zlib compression.
+ cPackBits = 32773
+ cDeflateOld = 32946 // Superseded by cDeflate.
+)
+
+// Photometric interpretation values (see p. 37 of the spec).
+const (
+ pWhiteIsZero = 0
+ pBlackIsZero = 1
+ pRGB = 2
+ pPaletted = 3
+ pTransMask = 4 // transparency mask
+ pCMYK = 5
+ pYCbCr = 6
+ pCIELab = 8
+)
+
+// Values for the tPredictor tag (page 64-65 of the spec).
+const (
+ prNone = 1
+ prHorizontal = 2
+)
+
+// Values for the tResolutionUnit tag (page 18).
+const (
+ resNone = 1
+ resPerInch = 2 // Dots per inch.
+ resPerCM = 3 // Dots per centimeter.
+)
+
+// imageMode represents the mode of the image.
+type imageMode int
+
+const (
+ mBilevel imageMode = iota
+ mPaletted
+ mGray
+ mGrayInvert
+ mRGB
+ mRGBA
+ mNRGBA
+)
+
+// CompressionType describes the type of compression used in Options.
+type CompressionType int
+
+const (
+ Uncompressed CompressionType = iota
+ Deflate
+)
+
+// specValue returns the compression type constant from the TIFF spec that
+// is equivalent to c.
+func (c CompressionType) specValue() uint32 {
+ switch c {
+ case Deflate:
+ return cDeflate
+ }
+ return cNone
+}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/lzw/reader.go b/Godeps/_workspace/src/golang.org/x/image/tiff/lzw/reader.go
new file mode 100644
index 000000000..dc9f7dd1d
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/lzw/reader.go
@@ -0,0 +1,277 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package lzw implements the Lempel-Ziv-Welch compressed data format,
+// described in T. A. Welch, ``A Technique for High-Performance Data
+// Compression'', Computer, 17(6) (June 1984), pp 8-19.
+//
+// In particular, it implements LZW as used by the TIFF file format, including
+// an "off by one" algorithmic difference when compared to standard LZW.
+package lzw
+
+/*
+This file was branched from src/pkg/compress/lzw/reader.go in the
+standard library. Differences from the original are marked with "NOTE".
+
+The tif_lzw.c file in the libtiff C library has this comment:
+
+----
+The 5.0 spec describes a different algorithm than Aldus
+implements. Specifically, Aldus does code length transitions
+one code earlier than should be done (for real LZW).
+Earlier versions of this library implemented the correct
+LZW algorithm, but emitted codes in a bit order opposite
+to the TIFF spec. Thus, to maintain compatibility w/ Aldus
+we interpret MSB-LSB ordered codes to be images written w/
+old versions of this library, but otherwise adhere to the
+Aldus "off by one" algorithm.
+----
+
+The Go code doesn't read (invalid) TIFF files written by old versions of
+libtiff, but the LZW algorithm in this package still differs from the one in
+Go's standard package library to accomodate this "off by one" in valid TIFFs.
+*/
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+)
+
+// Order specifies the bit ordering in an LZW data stream.
+type Order int
+
+const (
+ // LSB means Least Significant Bits first, as used in the GIF file format.
+ LSB Order = iota
+ // MSB means Most Significant Bits first, as used in the TIFF and PDF
+ // file formats.
+ MSB
+)
+
+const (
+ maxWidth = 12
+ decoderInvalidCode = 0xffff
+ flushBuffer = 1 << maxWidth
+)
+
+// decoder is the state from which the readXxx method converts a byte
+// stream into a code stream.
+type decoder struct {
+ r io.ByteReader
+ bits uint32
+ nBits uint
+ width uint
+ read func(*decoder) (uint16, error) // readLSB or readMSB
+ litWidth int // width in bits of literal codes
+ err error
+
+ // The first 1<<litWidth codes are literal codes.
+ // The next two codes mean clear and EOF.
+ // Other valid codes are in the range [lo, hi] where lo := clear + 2,
+ // with the upper bound incrementing on each code seen.
+ // overflow is the code at which hi overflows the code width. NOTE: TIFF's LZW is "off by one".
+ // last is the most recently seen code, or decoderInvalidCode.
+ clear, eof, hi, overflow, last uint16
+
+ // Each code c in [lo, hi] expands to two or more bytes. For c != hi:
+ // suffix[c] is the last of these bytes.
+ // prefix[c] is the code for all but the last byte.
+ // This code can either be a literal code or another code in [lo, c).
+ // The c == hi case is a special case.
+ suffix [1 << maxWidth]uint8
+ prefix [1 << maxWidth]uint16
+
+ // output is the temporary output buffer.
+ // Literal codes are accumulated from the start of the buffer.
+ // Non-literal codes decode to a sequence of suffixes that are first
+ // written right-to-left from the end of the buffer before being copied
+ // to the start of the buffer.
+ // It is flushed when it contains >= 1<<maxWidth bytes,
+ // so that there is always room to decode an entire code.
+ output [2 * 1 << maxWidth]byte
+ o int // write index into output
+ toRead []byte // bytes to return from Read
+}
+
+// readLSB returns the next code for "Least Significant Bits first" data.
+func (d *decoder) readLSB() (uint16, error) {
+ for d.nBits < d.width {
+ x, err := d.r.ReadByte()
+ if err != nil {
+ return 0, err
+ }
+ d.bits |= uint32(x) << d.nBits
+ d.nBits += 8
+ }
+ code := uint16(d.bits & (1<<d.width - 1))
+ d.bits >>= d.width
+ d.nBits -= d.width
+ return code, nil
+}
+
+// readMSB returns the next code for "Most Significant Bits first" data.
+func (d *decoder) readMSB() (uint16, error) {
+ for d.nBits < d.width {
+ x, err := d.r.ReadByte()
+ if err != nil {
+ return 0, err
+ }
+ d.bits |= uint32(x) << (24 - d.nBits)
+ d.nBits += 8
+ }
+ code := uint16(d.bits >> (32 - d.width))
+ d.bits <<= d.width
+ d.nBits -= d.width
+ return code, nil
+}
+
+func (d *decoder) Read(b []byte) (int, error) {
+ for {
+ if len(d.toRead) > 0 {
+ n := copy(b, d.toRead)
+ d.toRead = d.toRead[n:]
+ return n, nil
+ }
+ if d.err != nil {
+ return 0, d.err
+ }
+ d.decode()
+ }
+}
+
+// decode decompresses bytes from r and leaves them in d.toRead.
+// read specifies how to decode bytes into codes.
+// litWidth is the width in bits of literal codes.
+func (d *decoder) decode() {
+ // Loop over the code stream, converting codes into decompressed bytes.
+ for {
+ code, err := d.read(d)
+ if err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ d.err = err
+ d.flush()
+ return
+ }
+ switch {
+ case code < d.clear:
+ // We have a literal code.
+ d.output[d.o] = uint8(code)
+ d.o++
+ if d.last != decoderInvalidCode {
+ // Save what the hi code expands to.
+ d.suffix[d.hi] = uint8(code)
+ d.prefix[d.hi] = d.last
+ }
+ case code == d.clear:
+ d.width = 1 + uint(d.litWidth)
+ d.hi = d.eof
+ d.overflow = 1 << d.width
+ d.last = decoderInvalidCode
+ continue
+ case code == d.eof:
+ d.flush()
+ d.err = io.EOF
+ return
+ case code <= d.hi:
+ c, i := code, len(d.output)-1
+ if code == d.hi {
+ // code == hi is a special case which expands to the last expansion
+ // followed by the head of the last expansion. To find the head, we walk
+ // the prefix chain until we find a literal code.
+ c = d.last
+ for c >= d.clear {
+ c = d.prefix[c]
+ }
+ d.output[i] = uint8(c)
+ i--
+ c = d.last
+ }
+ // Copy the suffix chain into output and then write that to w.
+ for c >= d.clear {
+ d.output[i] = d.suffix[c]
+ i--
+ c = d.prefix[c]
+ }
+ d.output[i] = uint8(c)
+ d.o += copy(d.output[d.o:], d.output[i:])
+ if d.last != decoderInvalidCode {
+ // Save what the hi code expands to.
+ d.suffix[d.hi] = uint8(c)
+ d.prefix[d.hi] = d.last
+ }
+ default:
+ d.err = errors.New("lzw: invalid code")
+ d.flush()
+ return
+ }
+ d.last, d.hi = code, d.hi+1
+ if d.hi+1 >= d.overflow { // NOTE: the "+1" is where TIFF's LZW differs from the standard algorithm.
+ if d.width == maxWidth {
+ d.last = decoderInvalidCode
+ } else {
+ d.width++
+ d.overflow <<= 1
+ }
+ }
+ if d.o >= flushBuffer {
+ d.flush()
+ return
+ }
+ }
+}
+
+func (d *decoder) flush() {
+ d.toRead = d.output[:d.o]
+ d.o = 0
+}
+
+var errClosed = errors.New("lzw: reader/writer is closed")
+
+func (d *decoder) Close() error {
+ d.err = errClosed // in case any Reads come along
+ return nil
+}
+
+// NewReader creates a new io.ReadCloser.
+// Reads from the returned io.ReadCloser read and decompress data from r.
+// If r does not also implement io.ByteReader,
+// the decompressor may read more data than necessary from r.
+// It is the caller's responsibility to call Close on the ReadCloser when
+// finished reading.
+// The number of bits to use for literal codes, litWidth, must be in the
+// range [2,8] and is typically 8. It must equal the litWidth
+// used during compression.
+func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {
+ d := new(decoder)
+ switch order {
+ case LSB:
+ d.read = (*decoder).readLSB
+ case MSB:
+ d.read = (*decoder).readMSB
+ default:
+ d.err = errors.New("lzw: unknown order")
+ return d
+ }
+ if litWidth < 2 || 8 < litWidth {
+ d.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth)
+ return d
+ }
+ if br, ok := r.(io.ByteReader); ok {
+ d.r = br
+ } else {
+ d.r = bufio.NewReader(r)
+ }
+ d.litWidth = litWidth
+ d.width = 1 + uint(litWidth)
+ d.clear = uint16(1) << uint(litWidth)
+ d.eof, d.hi = d.clear+1, d.clear+1
+ d.overflow = uint16(1) << d.width
+ d.last = decoderInvalidCode
+
+ return d
+}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/reader.go b/Godeps/_workspace/src/golang.org/x/image/tiff/reader.go
new file mode 100644
index 000000000..714e3dda7
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/reader.go
@@ -0,0 +1,681 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package tiff implements a TIFF image decoder and encoder.
+//
+// The TIFF specification is at http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
+package tiff
+
+import (
+ "compress/zlib"
+ "encoding/binary"
+ "fmt"
+ "image"
+ "image/color"
+ "io"
+ "io/ioutil"
+ "math"
+
+ "golang.org/x/image/tiff/lzw"
+)
+
+// A FormatError reports that the input is not a valid TIFF image.
+type FormatError string
+
+func (e FormatError) Error() string {
+ return "tiff: invalid format: " + string(e)
+}
+
+// An UnsupportedError reports that the input uses a valid but
+// unimplemented feature.
+type UnsupportedError string
+
+func (e UnsupportedError) Error() string {
+ return "tiff: unsupported feature: " + string(e)
+}
+
+// An InternalError reports that an internal error was encountered.
+type InternalError string
+
+func (e InternalError) Error() string {
+ return "tiff: internal error: " + string(e)
+}
+
+var errNoPixels = FormatError("not enough pixel data")
+
+type decoder struct {
+ r io.ReaderAt
+ byteOrder binary.ByteOrder
+ config image.Config
+ mode imageMode
+ bpp uint
+ features map[int][]uint
+ palette []color.Color
+
+ buf []byte
+ off int // Current offset in buf.
+ v uint32 // Buffer value for reading with arbitrary bit depths.
+ nbits uint // Remaining number of bits in v.
+}
+
+// firstVal returns the first uint of the features entry with the given tag,
+// or 0 if the tag does not exist.
+func (d *decoder) firstVal(tag int) uint {
+ f := d.features[tag]
+ if len(f) == 0 {
+ return 0
+ }
+ return f[0]
+}
+
+// ifdUint decodes the IFD entry in p, which must be of the Byte, Short
+// or Long type, and returns the decoded uint values.
+func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
+ var raw []byte
+ if len(p) < ifdLen {
+ return nil, FormatError("bad IFD entry")
+ }
+
+ datatype := d.byteOrder.Uint16(p[2:4])
+ if dt := int(datatype); dt <= 0 || dt >= len(lengths) {
+ return nil, UnsupportedError("IFD entry datatype")
+ }
+
+ count := d.byteOrder.Uint32(p[4:8])
+ if count > math.MaxInt32/lengths[datatype] {
+ return nil, FormatError("IFD data too large")
+ }
+ if datalen := lengths[datatype] * count; datalen > 4 {
+ // The IFD contains a pointer to the real value.
+ raw = make([]byte, datalen)
+ _, err = d.r.ReadAt(raw, int64(d.byteOrder.Uint32(p[8:12])))
+ } else {
+ raw = p[8 : 8+datalen]
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ u = make([]uint, count)
+ switch datatype {
+ case dtByte:
+ for i := uint32(0); i < count; i++ {
+ u[i] = uint(raw[i])
+ }
+ case dtShort:
+ for i := uint32(0); i < count; i++ {
+ u[i] = uint(d.byteOrder.Uint16(raw[2*i : 2*(i+1)]))
+ }
+ case dtLong:
+ for i := uint32(0); i < count; i++ {
+ u[i] = uint(d.byteOrder.Uint32(raw[4*i : 4*(i+1)]))
+ }
+ default:
+ return nil, UnsupportedError("data type")
+ }
+ return u, nil
+}
+
+// parseIFD decides whether the the IFD entry in p is "interesting" and
+// stows away the data in the decoder.
+func (d *decoder) parseIFD(p []byte) error {
+ tag := d.byteOrder.Uint16(p[0:2])
+ switch tag {
+ case tBitsPerSample,
+ tExtraSamples,
+ tPhotometricInterpretation,
+ tCompression,
+ tPredictor,
+ tStripOffsets,
+ tStripByteCounts,
+ tRowsPerStrip,
+ tTileWidth,
+ tTileLength,
+ tTileOffsets,
+ tTileByteCounts,
+ tImageLength,
+ tImageWidth:
+ val, err := d.ifdUint(p)
+ if err != nil {
+ return err
+ }
+ d.features[int(tag)] = val
+ case tColorMap:
+ val, err := d.ifdUint(p)
+ if err != nil {
+ return err
+ }
+ numcolors := len(val) / 3
+ if len(val)%3 != 0 || numcolors <= 0 || numcolors > 256 {
+ return FormatError("bad ColorMap length")
+ }
+ d.palette = make([]color.Color, numcolors)
+ for i := 0; i < numcolors; i++ {
+ d.palette[i] = color.RGBA64{
+ uint16(val[i]),
+ uint16(val[i+numcolors]),
+ uint16(val[i+2*numcolors]),
+ 0xffff,
+ }
+ }
+ case tSampleFormat:
+ // Page 27 of the spec: If the SampleFormat is present and
+ // the value is not 1 [= unsigned integer data], a Baseline
+ // TIFF reader that cannot handle the SampleFormat value
+ // must terminate the import process gracefully.
+ val, err := d.ifdUint(p)
+ if err != nil {
+ return err
+ }
+ for _, v := range val {
+ if v != 1 {
+ return UnsupportedError("sample format")
+ }
+ }
+ }
+ return nil
+}
+
+// readBits reads n bits from the internal buffer starting at the current offset.
+func (d *decoder) readBits(n uint) (v uint32, ok bool) {
+ for d.nbits < n {
+ d.v <<= 8
+ if d.off >= len(d.buf) {
+ return 0, false
+ }
+ d.v |= uint32(d.buf[d.off])
+ d.off++
+ d.nbits += 8
+ }
+ d.nbits -= n
+ rv := d.v >> d.nbits
+ d.v &^= rv << d.nbits
+ return rv, true
+}
+
+// flushBits discards the unread bits in the buffer used by readBits.
+// It is used at the end of a line.
+func (d *decoder) flushBits() {
+ d.v = 0
+ d.nbits = 0
+}
+
+// minInt returns the smaller of x or y.
+func minInt(a, b int) int {
+ if a <= b {
+ return a
+ }
+ return b
+}
+
+// decode decodes the raw data of an image.
+// It reads from d.buf and writes the strip or tile into dst.
+func (d *decoder) decode(dst image.Image, xmin, ymin, xmax, ymax int) error {
+ d.off = 0
+
+ // Apply horizontal predictor if necessary.
+ // In this case, p contains the color difference to the preceding pixel.
+ // See page 64-65 of the spec.
+ if d.firstVal(tPredictor) == prHorizontal {
+ switch d.bpp {
+ case 16:
+ var off int
+ n := 2 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
+ for y := ymin; y < ymax; y++ {
+ off += n
+ for x := 0; x < (xmax-xmin-1)*n; x += 2 {
+ if off+2 > len(d.buf) {
+ return errNoPixels
+ }
+ v0 := d.byteOrder.Uint16(d.buf[off-n : off-n+2])
+ v1 := d.byteOrder.Uint16(d.buf[off : off+2])
+ d.byteOrder.PutUint16(d.buf[off:off+2], v1+v0)
+ off += 2
+ }
+ }
+ case 8:
+ var off int
+ n := 1 * len(d.features[tBitsPerSample]) // bytes per sample times samples per pixel
+ for y := ymin; y < ymax; y++ {
+ off += n
+ for x := 0; x < (xmax-xmin-1)*n; x++ {
+ if off >= len(d.buf) {
+ return errNoPixels
+ }
+ d.buf[off] += d.buf[off-n]
+ off++
+ }
+ }
+ case 1:
+ return UnsupportedError("horizontal predictor with 1 BitsPerSample")
+ }
+ }
+
+ rMaxX := minInt(xmax, dst.Bounds().Max.X)
+ rMaxY := minInt(ymax, dst.Bounds().Max.Y)
+ switch d.mode {
+ case mGray, mGrayInvert:
+ if d.bpp == 16 {
+ img := dst.(*image.Gray16)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ if d.off+2 > len(d.buf) {
+ return errNoPixels
+ }
+ v := d.byteOrder.Uint16(d.buf[d.off : d.off+2])
+ d.off += 2
+ if d.mode == mGrayInvert {
+ v = 0xffff - v
+ }
+ img.SetGray16(x, y, color.Gray16{v})
+ }
+ }
+ } else {
+ img := dst.(*image.Gray)
+ max := uint32((1 << d.bpp) - 1)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ v, ok := d.readBits(d.bpp)
+ if !ok {
+ return errNoPixels
+ }
+ v = v * 0xff / max
+ if d.mode == mGrayInvert {
+ v = 0xff - v
+ }
+ img.SetGray(x, y, color.Gray{uint8(v)})
+ }
+ d.flushBits()
+ }
+ }
+ case mPaletted:
+ img := dst.(*image.Paletted)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ v, ok := d.readBits(d.bpp)
+ if !ok {
+ return errNoPixels
+ }
+ img.SetColorIndex(x, y, uint8(v))
+ }
+ d.flushBits()
+ }
+ case mRGB:
+ if d.bpp == 16 {
+ img := dst.(*image.RGBA64)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ if d.off+6 > len(d.buf) {
+ return errNoPixels
+ }
+ r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
+ g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
+ b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
+ d.off += 6
+ img.SetRGBA64(x, y, color.RGBA64{r, g, b, 0xffff})
+ }
+ }
+ } else {
+ img := dst.(*image.RGBA)
+ for y := ymin; y < rMaxY; y++ {
+ min := img.PixOffset(xmin, y)
+ max := img.PixOffset(rMaxX, y)
+ off := (y - ymin) * (xmax - xmin) * 3
+ for i := min; i < max; i += 4 {
+ if off+3 > len(d.buf) {
+ return errNoPixels
+ }
+ img.Pix[i+0] = d.buf[off+0]
+ img.Pix[i+1] = d.buf[off+1]
+ img.Pix[i+2] = d.buf[off+2]
+ img.Pix[i+3] = 0xff
+ off += 3
+ }
+ }
+ }
+ case mNRGBA:
+ if d.bpp == 16 {
+ img := dst.(*image.NRGBA64)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ if d.off+8 > len(d.buf) {
+ return errNoPixels
+ }
+ r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
+ g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
+ b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
+ a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
+ d.off += 8
+ img.SetNRGBA64(x, y, color.NRGBA64{r, g, b, a})
+ }
+ }
+ } else {
+ img := dst.(*image.NRGBA)
+ for y := ymin; y < rMaxY; y++ {
+ min := img.PixOffset(xmin, y)
+ max := img.PixOffset(rMaxX, y)
+ i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
+ if i1 > len(d.buf) {
+ return errNoPixels
+ }
+ copy(img.Pix[min:max], d.buf[i0:i1])
+ }
+ }
+ case mRGBA:
+ if d.bpp == 16 {
+ img := dst.(*image.RGBA64)
+ for y := ymin; y < rMaxY; y++ {
+ for x := xmin; x < rMaxX; x++ {
+ if d.off+8 > len(d.buf) {
+ return errNoPixels
+ }
+ r := d.byteOrder.Uint16(d.buf[d.off+0 : d.off+2])
+ g := d.byteOrder.Uint16(d.buf[d.off+2 : d.off+4])
+ b := d.byteOrder.Uint16(d.buf[d.off+4 : d.off+6])
+ a := d.byteOrder.Uint16(d.buf[d.off+6 : d.off+8])
+ d.off += 8
+ img.SetRGBA64(x, y, color.RGBA64{r, g, b, a})
+ }
+ }
+ } else {
+ img := dst.(*image.RGBA)
+ for y := ymin; y < rMaxY; y++ {
+ min := img.PixOffset(xmin, y)
+ max := img.PixOffset(rMaxX, y)
+ i0, i1 := (y-ymin)*(xmax-xmin)*4, (y-ymin+1)*(xmax-xmin)*4
+ if i1 > len(d.buf) {
+ return errNoPixels
+ }
+ copy(img.Pix[min:max], d.buf[i0:i1])
+ }
+ }
+ }
+
+ return nil
+}
+
+func newDecoder(r io.Reader) (*decoder, error) {
+ d := &decoder{
+ r: newReaderAt(r),
+ features: make(map[int][]uint),
+ }
+
+ p := make([]byte, 8)
+ if _, err := d.r.ReadAt(p, 0); err != nil {
+ return nil, err
+ }
+ switch string(p[0:4]) {
+ case leHeader:
+ d.byteOrder = binary.LittleEndian
+ case beHeader:
+ d.byteOrder = binary.BigEndian
+ default:
+ return nil, FormatError("malformed header")
+ }
+
+ ifdOffset := int64(d.byteOrder.Uint32(p[4:8]))
+
+ // The first two bytes contain the number of entries (12 bytes each).
+ if _, err := d.r.ReadAt(p[0:2], ifdOffset); err != nil {
+ return nil, err
+ }
+ numItems := int(d.byteOrder.Uint16(p[0:2]))
+
+ // All IFD entries are read in one chunk.
+ p = make([]byte, ifdLen*numItems)
+ if _, err := d.r.ReadAt(p, ifdOffset+2); err != nil {
+ return nil, err
+ }
+
+ for i := 0; i < len(p); i += ifdLen {
+ if err := d.parseIFD(p[i : i+ifdLen]); err != nil {
+ return nil, err
+ }
+ }
+
+ d.config.Width = int(d.firstVal(tImageWidth))
+ d.config.Height = int(d.firstVal(tImageLength))
+
+ if _, ok := d.features[tBitsPerSample]; !ok {
+ return nil, FormatError("BitsPerSample tag missing")
+ }
+ d.bpp = d.firstVal(tBitsPerSample)
+ switch d.bpp {
+ case 0:
+ return nil, FormatError("BitsPerSample must not be 0")
+ case 1, 8, 16:
+ // Nothing to do, these are accepted by this implementation.
+ default:
+ return nil, UnsupportedError(fmt.Sprintf("BitsPerSample of %v", d.bpp))
+ }
+
+ // Determine the image mode.
+ switch d.firstVal(tPhotometricInterpretation) {
+ case pRGB:
+ if d.bpp == 16 {
+ for _, b := range d.features[tBitsPerSample] {
+ if b != 16 {
+ return nil, FormatError("wrong number of samples for 16bit RGB")
+ }
+ }
+ } else {
+ for _, b := range d.features[tBitsPerSample] {
+ if b != 8 {
+ return nil, FormatError("wrong number of samples for 8bit RGB")
+ }
+ }
+ }
+ // RGB images normally have 3 samples per pixel.
+ // If there are more, ExtraSamples (p. 31-32 of the spec)
+ // gives their meaning (usually an alpha channel).
+ //
+ // This implementation does not support extra samples
+ // of an unspecified type.
+ switch len(d.features[tBitsPerSample]) {
+ case 3:
+ d.mode = mRGB
+ if d.bpp == 16 {
+ d.config.ColorModel = color.RGBA64Model
+ } else {
+ d.config.ColorModel = color.RGBAModel
+ }
+ case 4:
+ switch d.firstVal(tExtraSamples) {
+ case 1:
+ d.mode = mRGBA
+ if d.bpp == 16 {
+ d.config.ColorModel = color.RGBA64Model
+ } else {
+ d.config.ColorModel = color.RGBAModel
+ }
+ case 2:
+ d.mode = mNRGBA
+ if d.bpp == 16 {
+ d.config.ColorModel = color.NRGBA64Model
+ } else {
+ d.config.ColorModel = color.NRGBAModel
+ }
+ default:
+ return nil, FormatError("wrong number of samples for RGB")
+ }
+ default:
+ return nil, FormatError("wrong number of samples for RGB")
+ }
+ case pPaletted:
+ d.mode = mPaletted
+ d.config.ColorModel = color.Palette(d.palette)
+ case pWhiteIsZero:
+ d.mode = mGrayInvert
+ if d.bpp == 16 {
+ d.config.ColorModel = color.Gray16Model
+ } else {
+ d.config.ColorModel = color.GrayModel
+ }
+ case pBlackIsZero:
+ d.mode = mGray
+ if d.bpp == 16 {
+ d.config.ColorModel = color.Gray16Model
+ } else {
+ d.config.ColorModel = color.GrayModel
+ }
+ default:
+ return nil, UnsupportedError("color model")
+ }
+
+ return d, nil
+}
+
+// DecodeConfig returns the color model and dimensions of a TIFF image without
+// decoding the entire image.
+func DecodeConfig(r io.Reader) (image.Config, error) {
+ d, err := newDecoder(r)
+ if err != nil {
+ return image.Config{}, err
+ }
+ return d.config, nil
+}
+
+// Decode reads a TIFF image from r and returns it as an image.Image.
+// The type of Image returned depends on the contents of the TIFF.
+func Decode(r io.Reader) (img image.Image, err error) {
+ d, err := newDecoder(r)
+ if err != nil {
+ return
+ }
+
+ blockPadding := false
+ blockWidth := d.config.Width
+ blockHeight := d.config.Height
+ blocksAcross := 1
+ blocksDown := 1
+
+ if d.config.Width == 0 {
+ blocksAcross = 0
+ }
+ if d.config.Height == 0 {
+ blocksDown = 0
+ }
+
+ var blockOffsets, blockCounts []uint
+
+ if int(d.firstVal(tTileWidth)) != 0 {
+ blockPadding = true
+
+ blockWidth = int(d.firstVal(tTileWidth))
+ blockHeight = int(d.firstVal(tTileLength))
+
+ if blockWidth != 0 {
+ blocksAcross = (d.config.Width + blockWidth - 1) / blockWidth
+ }
+ if blockHeight != 0 {
+ blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
+ }
+
+ blockCounts = d.features[tTileByteCounts]
+ blockOffsets = d.features[tTileOffsets]
+
+ } else {
+ if int(d.firstVal(tRowsPerStrip)) != 0 {
+ blockHeight = int(d.firstVal(tRowsPerStrip))
+ }
+
+ if blockHeight != 0 {
+ blocksDown = (d.config.Height + blockHeight - 1) / blockHeight
+ }
+
+ blockOffsets = d.features[tStripOffsets]
+ blockCounts = d.features[tStripByteCounts]
+ }
+
+ // Check if we have the right number of strips/tiles, offsets and counts.
+ if n := blocksAcross * blocksDown; len(blockOffsets) < n || len(blockCounts) < n {
+ return nil, FormatError("inconsistent header")
+ }
+
+ imgRect := image.Rect(0, 0, d.config.Width, d.config.Height)
+ switch d.mode {
+ case mGray, mGrayInvert:
+ if d.bpp == 16 {
+ img = image.NewGray16(imgRect)
+ } else {
+ img = image.NewGray(imgRect)
+ }
+ case mPaletted:
+ img = image.NewPaletted(imgRect, d.palette)
+ case mNRGBA:
+ if d.bpp == 16 {
+ img = image.NewNRGBA64(imgRect)
+ } else {
+ img = image.NewNRGBA(imgRect)
+ }
+ case mRGB, mRGBA:
+ if d.bpp == 16 {
+ img = image.NewRGBA64(imgRect)
+ } else {
+ img = image.NewRGBA(imgRect)
+ }
+ }
+
+ for i := 0; i < blocksAcross; i++ {
+ blkW := blockWidth
+ if !blockPadding && i == blocksAcross-1 && d.config.Width%blockWidth != 0 {
+ blkW = d.config.Width % blockWidth
+ }
+ for j := 0; j < blocksDown; j++ {
+ blkH := blockHeight
+ if !blockPadding && j == blocksDown-1 && d.config.Height%blockHeight != 0 {
+ blkH = d.config.Height % blockHeight
+ }
+ offset := int64(blockOffsets[j*blocksAcross+i])
+ n := int64(blockCounts[j*blocksAcross+i])
+ switch d.firstVal(tCompression) {
+
+ // According to the spec, Compression does not have a default value,
+ // but some tools interpret a missing Compression value as none so we do
+ // the same.
+ case cNone, 0:
+ if b, ok := d.r.(*buffer); ok {
+ d.buf, err = b.Slice(int(offset), int(n))
+ } else {
+ d.buf = make([]byte, n)
+ _, err = d.r.ReadAt(d.buf, offset)
+ }
+ case cLZW:
+ r := lzw.NewReader(io.NewSectionReader(d.r, offset, n), lzw.MSB, 8)
+ d.buf, err = ioutil.ReadAll(r)
+ r.Close()
+ case cDeflate, cDeflateOld:
+ var r io.ReadCloser
+ r, err = zlib.NewReader(io.NewSectionReader(d.r, offset, n))
+ if err != nil {
+ return nil, err
+ }
+ d.buf, err = ioutil.ReadAll(r)
+ r.Close()
+ case cPackBits:
+ d.buf, err = unpackBits(io.NewSectionReader(d.r, offset, n))
+ default:
+ err = UnsupportedError(fmt.Sprintf("compression value %d", d.firstVal(tCompression)))
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ xmin := i * blockWidth
+ ymin := j * blockHeight
+ xmax := xmin + blkW
+ ymax := ymin + blkH
+ err = d.decode(img, xmin, ymin, xmax, ymax)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+ return
+}
+
+func init() {
+ image.RegisterFormat("tiff", leHeader, Decode, DecodeConfig)
+ image.RegisterFormat("tiff", beHeader, Decode, DecodeConfig)
+}
diff --git a/Godeps/_workspace/src/golang.org/x/image/tiff/writer.go b/Godeps/_workspace/src/golang.org/x/image/tiff/writer.go
new file mode 100644
index 000000000..c8a01cea7
--- /dev/null
+++ b/Godeps/_workspace/src/golang.org/x/image/tiff/writer.go
@@ -0,0 +1,438 @@
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package tiff
+
+import (
+ "bytes"
+ "compress/zlib"
+ "encoding/binary"
+ "image"
+ "io"
+ "sort"
+)
+
+// The TIFF format allows to choose the order of the different elements freely.
+// The basic structure of a TIFF file written by this package is:
+//
+// 1. Header (8 bytes).
+// 2. Image data.
+// 3. Image File Directory (IFD).
+// 4. "Pointer area" for larger entries in the IFD.
+
+// We only write little-endian TIFF files.
+var enc = binary.LittleEndian
+
+// An ifdEntry is a single entry in an Image File Directory.
+// A value of type dtRational is composed of two 32-bit values,
+// thus data contains two uints (numerator and denominator) for a single number.
+type ifdEntry struct {
+ tag int
+ datatype int
+ data []uint32
+}
+
+func (e ifdEntry) putData(p []byte) {
+ for _, d := range e.data {
+ switch e.datatype {
+ case dtByte, dtASCII:
+ p[0] = byte(d)
+ p = p[1:]
+ case dtShort:
+ enc.PutUint16(p, uint16(d))
+ p = p[2:]
+ case dtLong, dtRational:
+ enc.PutUint32(p, uint32(d))
+ p = p[4:]
+ }
+ }
+}
+
+type byTag []ifdEntry
+
+func (d byTag) Len() int { return len(d) }
+func (d byTag) Less(i, j int) bool { return d[i].tag < d[j].tag }
+func (d byTag) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
+
+func encodeGray(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
+ if !predictor {
+ return writePix(w, pix, dy, dx, stride)
+ }
+ buf := make([]byte, dx)
+ for y := 0; y < dy; y++ {
+ min := y*stride + 0
+ max := y*stride + dx
+ off := 0
+ var v0 uint8
+ for i := min; i < max; i++ {
+ v1 := pix[i]
+ buf[off] = v1 - v0
+ v0 = v1
+ off++
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func encodeGray16(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
+ buf := make([]byte, dx*2)
+ for y := 0; y < dy; y++ {
+ min := y*stride + 0
+ max := y*stride + dx*2
+ off := 0
+ var v0 uint16
+ for i := min; i < max; i += 2 {
+ // An image.Gray16's Pix is in big-endian order.
+ v1 := uint16(pix[i])<<8 | uint16(pix[i+1])
+ if predictor {
+ v0, v1 = v1, v1-v0
+ }
+ // We only write little-endian TIFF files.
+ buf[off+0] = byte(v1)
+ buf[off+1] = byte(v1 >> 8)
+ off += 2
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func encodeRGBA(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
+ if !predictor {
+ return writePix(w, pix, dy, dx*4, stride)
+ }
+ buf := make([]byte, dx*4)
+ for y := 0; y < dy; y++ {
+ min := y*stride + 0
+ max := y*stride + dx*4
+ off := 0
+ var r0, g0, b0, a0 uint8
+ for i := min; i < max; i += 4 {
+ r1, g1, b1, a1 := pix[i+0], pix[i+1], pix[i+2], pix[i+3]
+ buf[off+0] = r1 - r0
+ buf[off+1] = g1 - g0
+ buf[off+2] = b1 - b0
+ buf[off+3] = a1 - a0
+ off += 4
+ r0, g0, b0, a0 = r1, g1, b1, a1
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func encodeRGBA64(w io.Writer, pix []uint8, dx, dy, stride int, predictor bool) error {
+ buf := make([]byte, dx*8)
+ for y := 0; y < dy; y++ {
+ min := y*stride + 0
+ max := y*stride + dx*8
+ off := 0
+ var r0, g0, b0, a0 uint16
+ for i := min; i < max; i += 8 {
+ // An image.RGBA64's Pix is in big-endian order.
+ r1 := uint16(pix[i+0])<<8 | uint16(pix[i+1])
+ g1 := uint16(pix[i+2])<<8 | uint16(pix[i+3])
+ b1 := uint16(pix[i+4])<<8 | uint16(pix[i+5])
+ a1 := uint16(pix[i+6])<<8 | uint16(pix[i+7])
+ if predictor {
+ r0, r1 = r1, r1-r0
+ g0, g1 = g1, g1-g0
+ b0, b1 = b1, b1-b0
+ a0, a1 = a1, a1-a0
+ }
+ // We only write little-endian TIFF files.
+ buf[off+0] = byte(r1)
+ buf[off+1] = byte(r1 >> 8)
+ buf[off+2] = byte(g1)
+ buf[off+3] = byte(g1 >> 8)
+ buf[off+4] = byte(b1)
+ buf[off+5] = byte(b1 >> 8)
+ buf[off+6] = byte(a1)
+ buf[off+7] = byte(a1 >> 8)
+ off += 8
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func encode(w io.Writer, m image.Image, predictor bool) error {
+ bounds := m.Bounds()
+ buf := make([]byte, 4*bounds.Dx())
+ for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
+ off := 0
+ if predictor {
+ var r0, g0, b0, a0 uint8
+ for x := bounds.Min.X; x < bounds.Max.X; x++ {
+ r, g, b, a := m.At(x, y).RGBA()
+ r1 := uint8(r >> 8)
+ g1 := uint8(g >> 8)
+ b1 := uint8(b >> 8)
+ a1 := uint8(a >> 8)
+ buf[off+0] = r1 - r0
+ buf[off+1] = g1 - g0
+ buf[off+2] = b1 - b0
+ buf[off+3] = a1 - a0
+ off += 4
+ r0, g0, b0, a0 = r1, g1, b1, a1
+ }
+ } else {
+ for x := bounds.Min.X; x < bounds.Max.X; x++ {
+ r, g, b, a := m.At(x, y).RGBA()
+ buf[off+0] = uint8(r >> 8)
+ buf[off+1] = uint8(g >> 8)
+ buf[off+2] = uint8(b >> 8)
+ buf[off+3] = uint8(a >> 8)
+ off += 4
+ }
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// writePix writes the internal byte array of an image to w. It is less general
+// but much faster then encode. writePix is used when pix directly
+// corresponds to one of the TIFF image types.
+func writePix(w io.Writer, pix []byte, nrows, length, stride int) error {
+ if length == stride {
+ _, err := w.Write(pix[:nrows*length])
+ return err
+ }
+ for ; nrows > 0; nrows-- {
+ if _, err := w.Write(pix[:length]); err != nil {
+ return err
+ }
+ pix = pix[stride:]
+ }
+ return nil
+}
+
+func writeIFD(w io.Writer, ifdOffset int, d []ifdEntry) error {
+ var buf [ifdLen]byte
+ // Make space for "pointer area" containing IFD entry data
+ // longer than 4 bytes.
+ parea := make([]byte, 1024)
+ pstart := ifdOffset + ifdLen*len(d) + 6
+ var o int // Current offset in parea.
+
+ // The IFD has to be written with the tags in ascending order.
+ sort.Sort(byTag(d))
+
+ // Write the number of entries in this IFD.
+ if err := binary.Write(w, enc, uint16(len(d))); err != nil {
+ return err
+ }
+ for _, ent := range d {
+ enc.PutUint16(buf[0:2], uint16(ent.tag))
+ enc.PutUint16(buf[2:4], uint16(ent.datatype))
+ count := uint32(len(ent.data))
+ if ent.datatype == dtRational {
+ count /= 2
+ }
+ enc.PutUint32(buf[4:8], count)
+ datalen := int(count * lengths[ent.datatype])
+ if datalen <= 4 {
+ ent.putData(buf[8:12])
+ } else {
+ if (o + datalen) > len(parea) {
+ newlen := len(parea) + 1024
+ for (o + datalen) > newlen {
+ newlen += 1024
+ }
+ newarea := make([]byte, newlen)
+ copy(newarea, parea)
+ parea = newarea
+ }
+ ent.putData(parea[o : o+datalen])
+ enc.PutUint32(buf[8:12], uint32(pstart+o))
+ o += datalen
+ }
+ if _, err := w.Write(buf[:]); err != nil {
+ return err
+ }
+ }
+ // The IFD ends with the offset of the next IFD in the file,
+ // or zero if it is the last one (page 14).
+ if err := binary.Write(w, enc, uint32(0)); err != nil {
+ return err
+ }
+ _, err := w.Write(parea[:o])
+ return err
+}
+
+// Options are the encoding parameters.
+type Options struct {
+ // Compression is the type of compression used.
+ Compression CompressionType
+ // Predictor determines whether a differencing predictor is used;
+ // if true, instead of each pixel's color, the color difference to the
+ // preceding one is saved. This improves the compression for certain
+ // types of images and compressors. For example, it works well for
+ // photos with Deflate compression.
+ Predictor bool
+}
+
+// Encode writes the image m to w. opt determines the options used for
+// encoding, such as the compression type. If opt is nil, an uncompressed
+// image is written.
+func Encode(w io.Writer, m image.Image, opt *Options) error {
+ d := m.Bounds().Size()
+
+ compression := uint32(cNone)
+ predictor := false
+ if opt != nil {
+ compression = opt.Compression.specValue()
+ // The predictor field is only used with LZW. See page 64 of the spec.
+ predictor = opt.Predictor && compression == cLZW
+ }
+
+ _, err := io.WriteString(w, leHeader)
+ if err != nil {
+ return err
+ }
+
+ // Compressed data is written into a buffer first, so that we
+ // know the compressed size.
+ var buf bytes.Buffer
+ // dst holds the destination for the pixel data of the image --
+ // either w or a writer to buf.
+ var dst io.Writer
+ // imageLen is the length of the pixel data in bytes.
+ // The offset of the IFD is imageLen + 8 header bytes.
+ var imageLen int
+
+ switch compression {
+ case cNone:
+ dst = w
+ // Write IFD offset before outputting pixel data.
+ switch m.(type) {
+ case *image.Paletted:
+ imageLen = d.X * d.Y * 1
+ case *image.Gray:
+ imageLen = d.X * d.Y * 1
+ case *image.Gray16:
+ imageLen = d.X * d.Y * 2
+ case *image.RGBA64:
+ imageLen = d.X * d.Y * 8
+ case *image.NRGBA64:
+ imageLen = d.X * d.Y * 8
+ default:
+ imageLen = d.X * d.Y * 4
+ }
+ err = binary.Write(w, enc, uint32(imageLen+8))
+ if err != nil {
+ return err
+ }
+ case cDeflate:
+ dst = zlib.NewWriter(&buf)
+ }
+
+ pr := uint32(prNone)
+ photometricInterpretation := uint32(pRGB)
+ samplesPerPixel := uint32(4)
+ bitsPerSample := []uint32{8, 8, 8, 8}
+ extraSamples := uint32(0)
+ colorMap := []uint32{}
+
+ if predictor {
+ pr = prHorizontal
+ }
+ switch m := m.(type) {
+ case *image.Paletted:
+ photometricInterpretation = pPaletted
+ samplesPerPixel = 1
+ bitsPerSample = []uint32{8}
+ colorMap = make([]uint32, 256*3)
+ for i := 0; i < 256 && i < len(m.Palette); i++ {
+ r, g, b, _ := m.Palette[i].RGBA()
+ colorMap[i+0*256] = uint32(r)
+ colorMap[i+1*256] = uint32(g)
+ colorMap[i+2*256] = uint32(b)
+ }
+ err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.Gray:
+ photometricInterpretation = pBlackIsZero
+ samplesPerPixel = 1
+ bitsPerSample = []uint32{8}
+ err = encodeGray(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.Gray16:
+ photometricInterpretation = pBlackIsZero
+ samplesPerPixel = 1
+ bitsPerSample = []uint32{16}
+ err = encodeGray16(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.NRGBA:
+ extraSamples = 2 // Unassociated alpha.
+ err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.NRGBA64:
+ extraSamples = 2 // Unassociated alpha.
+ bitsPerSample = []uint32{16, 16, 16, 16}
+ err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.RGBA:
+ extraSamples = 1 // Associated alpha.
+ err = encodeRGBA(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ case *image.RGBA64:
+ extraSamples = 1 // Associated alpha.
+ bitsPerSample = []uint32{16, 16, 16, 16}
+ err = encodeRGBA64(dst, m.Pix, d.X, d.Y, m.Stride, predictor)
+ default:
+ extraSamples = 1 // Associated alpha.
+ err = encode(dst, m, predictor)
+ }
+ if err != nil {
+ return err
+ }
+
+ if compression != cNone {
+ if err = dst.(io.Closer).Close(); err != nil {
+ return err
+ }
+ imageLen = buf.Len()
+ if err = binary.Write(w, enc, uint32(imageLen+8)); err != nil {
+ return err
+ }
+ if _, err = buf.WriteTo(w); err != nil {
+ return err
+ }
+ }
+
+ ifd := []ifdEntry{
+ {tImageWidth, dtShort, []uint32{uint32(d.X)}},
+ {tImageLength, dtShort, []uint32{uint32(d.Y)}},
+ {tBitsPerSample, dtShort, bitsPerSample},
+ {tCompression, dtShort, []uint32{compression}},
+ {tPhotometricInterpretation, dtShort, []uint32{photometricInterpretation}},
+ {tStripOffsets, dtLong, []uint32{8}},
+ {tSamplesPerPixel, dtShort, []uint32{samplesPerPixel}},
+ {tRowsPerStrip, dtShort, []uint32{uint32(d.Y)}},
+ {tStripByteCounts, dtLong, []uint32{uint32(imageLen)}},
+ // There is currently no support for storing the image
+ // resolution, so give a bogus value of 72x72 dpi.
+ {tXResolution, dtRational, []uint32{72, 1}},
+ {tYResolution, dtRational, []uint32{72, 1}},
+ {tResolutionUnit, dtShort, []uint32{resPerInch}},
+ }
+ if pr != prNone {
+ ifd = append(ifd, ifdEntry{tPredictor, dtShort, []uint32{pr}})
+ }
+ if len(colorMap) != 0 {
+ ifd = append(ifd, ifdEntry{tColorMap, dtShort, colorMap})
+ }
+ if extraSamples > 0 {
+ ifd = append(ifd, ifdEntry{tExtraSamples, dtShort, []uint32{extraSamples}})
+ }
+
+ return writeIFD(w, imageLen+8, ifd)
+}
diff --git a/NOTICE.txt b/NOTICE.txt
index f31472477..b7a7fbc1d 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -724,6 +724,77 @@ Legal Terms
Our home page can be found at
http://www.freetype.org
+
+--- end of FTL.TXT ---
+
+---
+This product contains a modified portion of 'gemoji', a collection of emoji images and names by Apple Inc. and other contributors.
---- end of FTL.TXT ---
+* HOMEPAGE:
+ * https://github.com/github/gemoji/blob/master/LICENSE
+
+* LICENSE:
+
+octocat, squirrel, shipit
+Copyright (c) 2013 GitHub Inc. All rights reserved.
+
+bowtie, neckbeard, fu
+Copyright (c) 2013 37signals, LLC. All rights reserved.
+
+feelsgood, finnadie, goberserk, godmode, hurtrealbad, rage 1-4, suspect
+Copyright (c) 2013 id Software. All rights reserved.
+
+trollface
+Copyright (c) 2013 whynne@deviantart. All rights reserved.
+
+All other images
+Copyright (c) 2013 Apple Inc. All rights reserved.
+
+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:
+
+The above copyright notice and this permission notice shall be included in all copies
+or substantial portions of the Software.
+
+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.
+
+---
+
+This product contains a modified portion of 'marked', a full-featured markdown parser and compiler, written in JavaScript. Built for speed.
+
+by Christopher Jeffrey
+
+* HOMEPAGE:
+ * https://github.com/chjj/marked
+
+* LICENSE:
+
+Copyright (c) 2011-2014, Christopher Jeffrey (https://github.com/chjj/)
+
+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:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+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.
diff --git a/api/admin.go b/api/admin.go
index 646597755..568d8f6e8 100644
--- a/api/admin.go
+++ b/api/admin.go
@@ -24,6 +24,7 @@ func InitAdmin(r *mux.Router) {
sr.Handle("/config", ApiUserRequired(getConfig)).Methods("GET")
sr.Handle("/save_config", ApiUserRequired(saveConfig)).Methods("POST")
sr.Handle("/client_props", ApiAppHandler(getClientProperties)).Methods("GET")
+ sr.Handle("/test_email", ApiUserRequired(testEmail)).Methods("POST")
}
func getLogs(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -34,7 +35,7 @@ func getLogs(c *Context, w http.ResponseWriter, r *http.Request) {
var lines []string
- if utils.Cfg.LogSettings.FileEnable {
+ if utils.Cfg.LogSettings.EnableFile {
file, err := os.Open(utils.GetLogFileLocation(utils.Cfg.LogSettings.FileLocation))
if err != nil {
@@ -81,7 +82,7 @@ func saveConfig(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- if len(cfg.ServiceSettings.Port) == 0 {
+ if len(cfg.ServiceSettings.ListenAddress) == 0 {
c.SetInvalidParam("saveConfig", "config")
return
}
@@ -98,3 +99,29 @@ func saveConfig(c *Context, w http.ResponseWriter, r *http.Request) {
json := utils.Cfg.ToJson()
w.Write([]byte(json))
}
+
+func testEmail(c *Context, w http.ResponseWriter, r *http.Request) {
+ if !c.HasSystemAdminPermissions("testEmail") {
+ return
+ }
+
+ cfg := model.ConfigFromJson(r.Body)
+ if cfg == nil {
+ c.SetInvalidParam("testEmail", "config")
+ return
+ }
+
+ if result := <-Srv.Store.User().Get(c.Session.UserId); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ if err := utils.SendMailUsingConfig(result.Data.(*model.User).Email, "Mattermost - Testing Email Settings", "<br/><br/><br/>It appears your Mattermost email is setup correctly!", cfg); err != nil {
+ c.Err = err
+ return
+ }
+ }
+
+ m := make(map[string]string)
+ m["SUCCESS"] = "true"
+ w.Write([]byte(model.MapToJson(m)))
+}
diff --git a/api/admin_test.go b/api/admin_test.go
index e1778b5ac..ad7ac08f8 100644
--- a/api/admin_test.go
+++ b/api/admin_test.go
@@ -83,7 +83,7 @@ func TestGetConfig(t *testing.T) {
} else {
cfg := result.Data.(*model.Config)
- if len(cfg.ServiceSettings.SiteName) == 0 {
+ if len(cfg.TeamSettings.SiteName) == 0 {
t.Fatal()
}
}
@@ -117,8 +117,36 @@ func TestSaveConfig(t *testing.T) {
} else {
cfg := result.Data.(*model.Config)
- if len(cfg.ServiceSettings.SiteName) == 0 {
+ if len(cfg.TeamSettings.SiteName) == 0 {
t.Fatal()
}
}
}
+
+func TestEmailTest(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
+ store.Must(Srv.Store.User().VerifyEmail(user.Id))
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ if _, err := Client.TestEmail(utils.Cfg); err == nil {
+ t.Fatal("Shouldn't have permissions")
+ }
+
+ c := &Context{}
+ c.RequestId = model.NewId()
+ c.IpAddress = "cmd_line"
+ UpdateRoles(c, user, model.ROLE_SYSTEM_ADMIN)
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ if _, err := Client.TestEmail(utils.Cfg); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/api/api.go b/api/api.go
index c8f97c5af..a50cce946 100644
--- a/api/api.go
+++ b/api/api.go
@@ -44,6 +44,7 @@ func InitApi() {
InitCommand(r)
InitAdmin(r)
InitOAuth(r)
+ InitWebhook(r)
templatesDir := utils.FindDir("api/templates")
l4g.Debug("Parsing server templates at %v", templatesDir)
diff --git a/api/api_test.go b/api/api_test.go
index 642db581e..761f3e33f 100644
--- a/api/api_test.go
+++ b/api/api_test.go
@@ -14,10 +14,11 @@ var Client *model.Client
func Setup() {
if Srv == nil {
utils.LoadConfig("config.json")
+ utils.Cfg.TeamSettings.MaxUsersPerTeam = 50
NewServer()
StartServer()
InitApi()
- Client = model.NewClient("http://localhost:" + utils.Cfg.ServiceSettings.Port)
+ Client = model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
}
}
diff --git a/api/channel.go b/api/channel.go
index 63acaa8d1..896e22793 100644
--- a/api/channel.go
+++ b/api/channel.go
@@ -121,11 +121,7 @@ func CreateDirectChannel(c *Context, otherUserId string) (*model.Channel, *model
channel := new(model.Channel)
channel.DisplayName = ""
- if otherUserId > c.Session.UserId {
- channel.Name = c.Session.UserId + "__" + otherUserId
- } else {
- channel.Name = otherUserId + "__" + c.Session.UserId
- }
+ channel.Name = model.GetDMNameFromIds(otherUserId, c.Session.UserId)
channel.TeamId = c.Session.TeamId
channel.Description = ""
diff --git a/api/channel_test.go b/api/channel_test.go
index 14bfe1cf7..7845ac499 100644
--- a/api/channel_test.go
+++ b/api/channel_test.go
@@ -627,7 +627,7 @@ func TestGetChannelExtraInfo(t *testing.T) {
currentEtag = cache_result.Etag
}
- Client2 := model.NewClient("http://localhost:" + utils.Cfg.ServiceSettings.Port)
+ Client2 := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
user2 := &model.User{TeamId: team.Id, Email: model.NewId() + "tester2@test.com", Nickname: "Tester 2", Password: "pwd"}
user2 = Client2.Must(Client2.CreateUser(user2, "")).Data.(*model.User)
diff --git a/api/command.go b/api/command.go
index bc55f206b..0d2f7597b 100644
--- a/api/command.go
+++ b/api/command.go
@@ -215,8 +215,8 @@ func joinCommand(c *Context, command *model.Command) bool {
func loadTestCommand(c *Context, command *model.Command) bool {
cmd := "/loadtest"
- // This command is only available when AllowTesting is true
- if !utils.Cfg.ServiceSettings.AllowTesting {
+ // This command is only available when EnableTesting is true
+ if !utils.Cfg.ServiceSettings.EnableTesting {
return false
}
diff --git a/api/context.go b/api/context.go
index 02716bb33..d90fbd9ee 100644
--- a/api/context.go
+++ b/api/context.go
@@ -107,21 +107,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
isTokenFromQueryString = true
}
- protocol := "http"
-
- // If the request came from the ELB then assume this is produciton
- // and redirect all http requests to https
- if utils.Cfg.ServiceSettings.UseSSL {
- forwardProto := r.Header.Get(model.HEADER_FORWARDED_PROTO)
- if forwardProto == "http" {
- l4g.Info("redirecting http request to https for %v", r.URL.Path)
- http.Redirect(w, r, "https://"+r.Host, http.StatusTemporaryRedirect)
- return
- } else {
- protocol = "https"
- }
- }
-
+ protocol := GetProtocol(r)
c.setSiteURL(protocol + "://" + r.Host)
w.Header().Set(model.HEADER_REQUEST_ID, c.RequestId)
@@ -209,6 +195,14 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
+func GetProtocol(r *http.Request) string {
+ if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" {
+ return "https"
+ } else {
+ return "http"
+ }
+}
+
func (c *Context) LogAudit(extraInfo string) {
audit := &model.Audit{UserId: c.Session.UserId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id}
if r := <-Srv.Store.Audit().Save(audit); r.Err != nil {
@@ -385,6 +379,11 @@ func (c *Context) GetSiteURL() string {
func GetIpAddress(r *http.Request) string {
address := r.Header.Get(model.HEADER_FORWARDED)
+
+ if len(address) == 0 {
+ address = r.Header.Get(model.HEADER_REAL_IP)
+ }
+
if len(address) == 0 {
address, _, _ = net.SplitHostPort(r.RemoteAddr)
}
@@ -457,25 +456,19 @@ func IsPrivateIpAddress(ipAddress string) bool {
}
func RenderWebError(err *model.AppError, w http.ResponseWriter, r *http.Request) {
+ props := make(map[string]string)
+ props["Message"] = err.Message
+ props["Details"] = err.DetailedError
- protocol := "http"
- if utils.Cfg.ServiceSettings.UseSSL {
- forwardProto := r.Header.Get(model.HEADER_FORWARDED_PROTO)
- if forwardProto != "http" {
- protocol = "https"
- }
+ pathParts := strings.Split(r.URL.Path, "/")
+ if len(pathParts) > 1 {
+ props["SiteURL"] = GetProtocol(r) + "://" + r.Host + "/" + pathParts[1]
+ } else {
+ props["SiteURL"] = GetProtocol(r) + "://" + r.Host
}
- SiteURL := protocol + "://" + r.Host
-
- m := make(map[string]string)
- m["Message"] = err.Message
- m["Details"] = err.DetailedError
- m["SiteName"] = utils.Cfg.ServiceSettings.SiteName
- m["SiteURL"] = SiteURL
-
w.WriteHeader(err.StatusCode)
- ServerTemplates.ExecuteTemplate(w, "error.html", m)
+ ServerTemplates.ExecuteTemplate(w, "error.html", Page{Props: props, ClientProps: utils.ClientProperties})
}
func Handle404(w http.ResponseWriter, r *http.Request) {
diff --git a/api/export.go b/api/export.go
index 9345f892f..aff34073f 100644
--- a/api/export.go
+++ b/api/export.go
@@ -87,7 +87,7 @@ func ExportTeams(writer ExportWriter, options *ExportOptions) *model.AppError {
// Get the teams
var teams []*model.Team
if len(options.TeamsToExport) == 0 {
- if result := <-Srv.Store.Team().GetForExport(); result.Err != nil {
+ if result := <-Srv.Store.Team().GetAll(); result.Err != nil {
return result.Err
} else {
teams = result.Data.([]*model.Team)
@@ -278,11 +278,11 @@ func copyDirToExportWriter(writer ExportWriter, inPath string, outPath string) *
}
func ExportLocalStorage(writer ExportWriter, options *ExportOptions, teamId string) *model.AppError {
- teamDir := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + teamId
+ teamDir := utils.Cfg.FileSettings.Directory + "teams/" + teamId
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
return model.NewAppError("ExportLocalStorage", "S3 is not supported for local storage export.", "")
- } else if utils.Cfg.ServiceSettings.UseLocalStorage && len(utils.Cfg.ServiceSettings.StorageDirectory) > 0 {
+ } else if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
if err := copyDirToExportWriter(writer, teamDir, EXPORT_LOCAL_STORAGE_FOLDER); err != nil {
return err
}
diff --git a/api/file.go b/api/file.go
index 3602b5ed4..be8fc5456 100644
--- a/api/file.go
+++ b/api/file.go
@@ -5,15 +5,15 @@ package api
import (
"bytes"
- "code.google.com/p/graphics-go/graphics"
l4g "code.google.com/p/log4go"
"fmt"
+ "github.com/disintegration/imaging"
"github.com/goamz/goamz/aws"
"github.com/goamz/goamz/s3"
"github.com/gorilla/mux"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/utils"
- "github.com/nfnt/resize"
+ "github.com/mssola/user_agent"
"github.com/rwcarlsen/goexif/exif"
_ "golang.org/x/image/bmp"
"image"
@@ -23,7 +23,6 @@ import (
"image/jpeg"
"io"
"io/ioutil"
- "math"
"mime"
"net/http"
"net/url"
@@ -69,8 +68,8 @@ func InitFile(r *mux.Router) {
}
func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) {
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
- c.Err = model.NewAppError("uploadFile", "Unable to upload file. Amazon S3 not configured and local server storage turned off. ", "")
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
+ c.Err = model.NewAppError("uploadFile", "Unable to upload file. Image storage is not configured.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
@@ -162,7 +161,7 @@ func fireAndForgetHandleImages(filenames []string, fileData [][]byte, teamId, ch
name := filename[:strings.LastIndex(filename, ".")]
go func() {
// Decode image bytes into Image object
- img, _, err := image.Decode(bytes.NewReader(fileData[i]))
+ img, imgType, err := image.Decode(bytes.NewReader(fileData[i]))
if err != nil {
l4g.Error("Unable to decode image channelId=%v userId=%v filename=%v err=%v", channelId, userId, filename, err)
return
@@ -174,51 +173,34 @@ func fireAndForgetHandleImages(filenames []string, fileData [][]byte, teamId, ch
// Get the image's orientation and ignore any errors since not all images will have orientation data
orientation, _ := getImageOrientation(fileData[i])
- // Create a temporary image that will be manipulated and then used to make the thumbnail and preview image
- var temp *image.RGBA
- switch orientation {
- case Upright, UprightMirrored, UpsideDown, UpsideDownMirrored:
- temp = image.NewRGBA(img.Bounds())
- case RotatedCCW, RotatedCCWMirrored, RotatedCW, RotatedCWMirrored:
- bounds := img.Bounds()
- temp = image.NewRGBA(image.Rect(bounds.Min.Y, bounds.Min.X, bounds.Max.Y, bounds.Max.X))
-
- width, height = height, width
+ if imgType == "png" {
+ dst := image.NewRGBA(img.Bounds())
+ draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
+ draw.Draw(dst, dst.Bounds(), img, img.Bounds().Min, draw.Over)
+ img = dst
}
- // Draw a white background since JPEGs lack transparency
- draw.Draw(temp, temp.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
-
- // Copy the original image onto the temporary one while rotating it as necessary
switch orientation {
- case UpsideDown, UpsideDownMirrored:
- // rotate 180 degrees
- err := graphics.Rotate(temp, img, &graphics.RotateOptions{Angle: math.Pi})
- if err != nil {
- l4g.Error("Unable to rotate image")
- }
- case RotatedCW, RotatedCWMirrored:
- // rotate 90 degrees CCW
- graphics.Rotate(temp, img, &graphics.RotateOptions{Angle: 3 * math.Pi / 2})
- if err != nil {
- l4g.Error("Unable to rotate image")
- }
- case RotatedCCW, RotatedCCWMirrored:
- // rotate 90 degrees CW
- graphics.Rotate(temp, img, &graphics.RotateOptions{Angle: math.Pi / 2})
- if err != nil {
- l4g.Error("Unable to rotate image")
- }
- case Upright, UprightMirrored:
- draw.Draw(temp, temp.Bounds(), img, img.Bounds().Min, draw.Over)
+ case UprightMirrored:
+ img = imaging.FlipH(img)
+ case UpsideDown:
+ img = imaging.Rotate180(img)
+ case UpsideDownMirrored:
+ img = imaging.FlipV(img)
+ case RotatedCWMirrored:
+ img = imaging.Transpose(img)
+ case RotatedCCW:
+ img = imaging.Rotate270(img)
+ case RotatedCCWMirrored:
+ img = imaging.Transverse(img)
+ case RotatedCW:
+ img = imaging.Rotate90(img)
}
- img = temp
-
// Create thumbnail
go func() {
- thumbWidth := float64(utils.Cfg.ImageSettings.ThumbnailWidth)
- thumbHeight := float64(utils.Cfg.ImageSettings.ThumbnailHeight)
+ thumbWidth := float64(utils.Cfg.FileSettings.ThumbnailWidth)
+ thumbHeight := float64(utils.Cfg.FileSettings.ThumbnailHeight)
imgWidth := float64(width)
imgHeight := float64(height)
@@ -226,9 +208,9 @@ func fireAndForgetHandleImages(filenames []string, fileData [][]byte, teamId, ch
if imgHeight < thumbHeight && imgWidth < thumbWidth {
thumbnail = img
} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
- thumbnail = resize.Resize(0, utils.Cfg.ImageSettings.ThumbnailHeight, img, resize.Lanczos3)
+ thumbnail = imaging.Resize(img, 0, utils.Cfg.FileSettings.ThumbnailHeight, imaging.Lanczos)
} else {
- thumbnail = resize.Resize(utils.Cfg.ImageSettings.ThumbnailWidth, 0, img, resize.Lanczos3)
+ thumbnail = imaging.Resize(img, utils.Cfg.FileSettings.ThumbnailWidth, 0, imaging.Lanczos)
}
buf := new(bytes.Buffer)
@@ -247,8 +229,8 @@ func fireAndForgetHandleImages(filenames []string, fileData [][]byte, teamId, ch
// Create preview
go func() {
var preview image.Image
- if width > int(utils.Cfg.ImageSettings.PreviewWidth) {
- preview = resize.Resize(utils.Cfg.ImageSettings.PreviewWidth, utils.Cfg.ImageSettings.PreviewHeight, img, resize.Lanczos3)
+ if width > int(utils.Cfg.FileSettings.PreviewWidth) {
+ preview = imaging.Resize(img, utils.Cfg.FileSettings.PreviewWidth, utils.Cfg.FileSettings.PreviewHeight, imaging.Lanczos)
} else {
preview = img
}
@@ -294,8 +276,8 @@ type ImageGetResult struct {
}
func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) {
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
- c.Err = model.NewAppError("getFileInfo", "Unable to get file info. Amazon S3 not configured and local server storage turned off. ", "")
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
+ c.Err = model.NewAppError("uploadFile", "Unable to get file info. Image storage is not configured.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
@@ -357,8 +339,8 @@ func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) {
}
func getFile(c *Context, w http.ResponseWriter, r *http.Request) {
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
- c.Err = model.NewAppError("getFile", "Unable to get file. Amazon S3 not configured and local server storage turned off. ", "")
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
+ c.Err = model.NewAppError("uploadFile", "Unable to get file. Image storage is not configured.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
@@ -400,7 +382,7 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) {
asyncGetFile(path, fileData)
if len(hash) > 0 && len(data) > 0 && len(teamId) == 26 {
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.PublicLinkSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt)) {
c.Err = model.NewAppError("getFile", "The public link does not appear to be valid", "")
return
}
@@ -426,6 +408,19 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=2592000, public")
w.Header().Set("Content-Length", strconv.Itoa(len(f)))
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(filename)))
+
+ // attach extra headers to trigger a download on IE and Edge
+ ua := user_agent.New(r.UserAgent())
+ bname, _ := ua.Browser()
+
+ if bname == "Edge" || bname == "Internet Explorer" {
+ // trim off anything before the final / so we just get the file's name
+ parts := strings.Split(filename, "/")
+
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", "attachment;filename=\""+parts[len(parts)-1]+"\"")
+ }
+
w.Write(f)
}
@@ -442,17 +437,17 @@ func asyncGetFile(path string, fileData chan []byte) {
}
func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) {
- if !utils.Cfg.TeamSettings.AllowPublicLink {
- c.Err = model.NewAppError("getPublicLink", "Public links have been disabled", "")
- c.Err.StatusCode = http.StatusForbidden
- }
-
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
- c.Err = model.NewAppError("getPublicLink", "Unable to upload file. Amazon S3 not configured and local server storage turned off. ", "")
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
+ c.Err = model.NewAppError("uploadFile", "Unable to get link. Image storage is not configured.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
+ if !utils.Cfg.FileSettings.EnablePublicLink {
+ c.Err = model.NewAppError("getPublicLink", "Public links have been disabled", "")
+ c.Err.StatusCode = http.StatusForbidden
+ }
+
props := model.MapFromJson(r.Body)
filename := props["filename"]
@@ -478,7 +473,7 @@ func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) {
newProps["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(newProps)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.PublicLinkSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt))
url := fmt.Sprintf("%s/api/v1/files/get/%s/%s/%s?d=%s&h=%s&t=%s", c.GetSiteURL(), channelId, userId, filename, url.QueryEscape(data), url.QueryEscape(hash), c.Session.TeamId)
@@ -511,13 +506,13 @@ func getExport(c *Context, w http.ResponseWriter, r *http.Request) {
func writeFile(f []byte, path string) *model.AppError {
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
ext := filepath.Ext(path)
@@ -534,12 +529,12 @@ func writeFile(f []byte, path string) *model.AppError {
if err != nil {
return model.NewAppError("writeFile", "Encountered an error writing to S3", err.Error())
}
- } else if utils.Cfg.ServiceSettings.UseLocalStorage && len(utils.Cfg.ServiceSettings.StorageDirectory) > 0 {
- if err := os.MkdirAll(filepath.Dir(utils.Cfg.ServiceSettings.StorageDirectory+path), 0774); err != nil {
+ } else if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
+ if err := os.MkdirAll(filepath.Dir(utils.Cfg.FileSettings.Directory+path), 0774); err != nil {
return model.NewAppError("writeFile", "Encountered an error creating the directory for the new file", err.Error())
}
- if err := ioutil.WriteFile(utils.Cfg.ServiceSettings.StorageDirectory+path, f, 0644); err != nil {
+ if err := ioutil.WriteFile(utils.Cfg.FileSettings.Directory+path, f, 0644); err != nil {
return model.NewAppError("writeFile", "Encountered an error writing to local server storage", err.Error())
}
} else {
@@ -551,13 +546,13 @@ func writeFile(f []byte, path string) *model.AppError {
func readFile(path string) ([]byte, *model.AppError) {
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
// try to get the file from S3 with some basic retry logic
tries := 0
@@ -573,8 +568,8 @@ func readFile(path string) ([]byte, *model.AppError) {
}
time.Sleep(3000 * time.Millisecond)
}
- } else if utils.Cfg.ServiceSettings.UseLocalStorage && len(utils.Cfg.ServiceSettings.StorageDirectory) > 0 {
- if f, err := ioutil.ReadFile(utils.Cfg.ServiceSettings.StorageDirectory + path); err != nil {
+ } else if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
+ if f, err := ioutil.ReadFile(utils.Cfg.FileSettings.Directory + path); err != nil {
return nil, model.NewAppError("readFile", "Encountered an error reading from local server storage", err.Error())
} else {
return f, nil
@@ -585,14 +580,14 @@ func readFile(path string) ([]byte, *model.AppError) {
}
func openFileWriteStream(path string) (io.Writer, *model.AppError) {
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
return nil, model.NewAppError("openFileWriteStream", "S3 is not supported.", "")
- } else if utils.Cfg.ServiceSettings.UseLocalStorage && len(utils.Cfg.ServiceSettings.StorageDirectory) > 0 {
- if err := os.MkdirAll(filepath.Dir(utils.Cfg.ServiceSettings.StorageDirectory+path), 0774); err != nil {
+ } else if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
+ if err := os.MkdirAll(filepath.Dir(utils.Cfg.FileSettings.Directory+path), 0774); err != nil {
return nil, model.NewAppError("openFileWriteStream", "Encountered an error creating the directory for the new file", err.Error())
}
- if fileHandle, err := os.Create(utils.Cfg.ServiceSettings.StorageDirectory + path); err != nil {
+ if fileHandle, err := os.Create(utils.Cfg.FileSettings.Directory + path); err != nil {
return nil, model.NewAppError("openFileWriteStream", "Encountered an error writing to local server storage", err.Error())
} else {
fileHandle.Chmod(0644)
diff --git a/api/file_benchmark_test.go b/api/file_benchmark_test.go
index 251ff7793..47f8bff43 100644
--- a/api/file_benchmark_test.go
+++ b/api/file_benchmark_test.go
@@ -38,7 +38,7 @@ func BenchmarkGetFile(b *testing.B) {
newProps["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(newProps)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.PublicLinkSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt))
// wait a bit for files to ready
time.Sleep(5 * time.Second)
diff --git a/api/file_test.go b/api/file_test.go
index eb1fcf2ce..657c08131 100644
--- a/api/file_test.go
+++ b/api/file_test.go
@@ -68,7 +68,7 @@ func TestUploadFile(t *testing.T) {
}
resp, appErr := Client.UploadFile("/files/upload", body.Bytes(), writer.FormDataContentType())
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
if appErr != nil {
t.Fatal(appErr)
}
@@ -81,11 +81,11 @@ func TestUploadFile(t *testing.T) {
fileId := strings.Split(filename, ".")[0]
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
// wait a bit for files to ready
time.Sleep(5 * time.Second)
@@ -104,7 +104,7 @@ func TestUploadFile(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- } else if utils.Cfg.ServiceSettings.UseLocalStorage && len(utils.Cfg.ServiceSettings.StorageDirectory) > 0 {
+ } else if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
filenames := strings.Split(resp.Data.(*model.FileUploadResponse).Filenames[0], "/")
filename := filenames[len(filenames)-2] + "/" + filenames[len(filenames)-1]
if strings.Contains(filename, "../") {
@@ -115,17 +115,17 @@ func TestUploadFile(t *testing.T) {
// wait a bit for files to ready
time.Sleep(5 * time.Second)
- path := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
+ path := utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
@@ -151,7 +151,7 @@ func TestGetFile(t *testing.T) {
channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
- if utils.IsS3Configured() || utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName != "" {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
@@ -222,7 +222,7 @@ func TestGetFile(t *testing.T) {
newProps["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(newProps)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.PublicLinkSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt))
Client.LoginByEmail(team2.Name, user2.Email, "pwd")
@@ -262,13 +262,13 @@ func TestGetFile(t *testing.T) {
t.Fatal("Should have errored - user not logged in and link not public")
}
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
filenames := strings.Split(resp.Data.(*model.FileUploadResponse).Filenames[0], "/")
filename := filenames[len(filenames)-2] + "/" + filenames[len(filenames)-1]
@@ -293,17 +293,17 @@ func TestGetFile(t *testing.T) {
filename := filenames[len(filenames)-2] + "/" + filenames[len(filenames)-1]
fileId := strings.Split(filename, ".")[0]
- path := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
+ path := utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
@@ -334,7 +334,7 @@ func TestGetPublicLink(t *testing.T) {
channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
- if utils.IsS3Configured() || utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName != "" {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
@@ -410,14 +410,14 @@ func TestGetPublicLink(t *testing.T) {
t.Fatal("should have errored, user not member of channel")
}
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
// perform clean-up on s3
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
filenames := strings.Split(resp.Data.(*model.FileUploadResponse).Filenames[0], "/")
filename := filenames[len(filenames)-2] + "/" + filenames[len(filenames)-1]
@@ -442,17 +442,17 @@ func TestGetPublicLink(t *testing.T) {
filename := filenames[len(filenames)-2] + "/" + filenames[len(filenames)-1]
fileId := strings.Split(filename, ".")[0]
- path := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
+ path := utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + filename
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_thumb.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
- path = utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
+ path = utils.Cfg.FileSettings.Directory + "teams/" + team.Id + "/channels/" + channel1.Id + "/users/" + user1.Id + "/" + fileId + "_preview.jpg"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
diff --git a/api/import.go b/api/import.go
index e3f314d20..c465825b4 100644
--- a/api/import.go
+++ b/api/import.go
@@ -6,7 +6,6 @@ package api
import (
l4g "code.google.com/p/log4go"
"github.com/mattermost/platform/model"
- "github.com/mattermost/platform/utils"
)
//
@@ -24,9 +23,6 @@ func ImportPost(post *model.Post) {
func ImportUser(user *model.User) *model.User {
user.MakeNonNil()
- if len(user.Props["theme"]) == 0 {
- user.AddProp("theme", utils.Cfg.TeamSettings.DefaultThemeColor)
- }
if result := <-Srv.Store.User().Save(user); result.Err != nil {
l4g.Error("Error saving user. err=%v", result.Err)
diff --git a/api/post.go b/api/post.go
index 21bc35b97..0379f6af5 100644
--- a/api/post.go
+++ b/api/post.go
@@ -25,7 +25,6 @@ func InitPost(r *mux.Router) {
sr := r.PathPrefix("/channels/{id:[A-Za-z0-9]+}").Subrouter()
sr.Handle("/create", ApiUserRequired(createPost)).Methods("POST")
- sr.Handle("/valet_create", ApiUserRequired(createValetPost)).Methods("POST")
sr.Handle("/update", ApiUserRequired(updatePost)).Methods("POST")
sr.Handle("/posts/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequiredActivity(getPosts, false)).Methods("GET")
sr.Handle("/posts/{time:[0-9]+}", ApiUserRequiredActivity(getPostsSince, false)).Methods("GET")
@@ -60,75 +59,6 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
-func createValetPost(c *Context, w http.ResponseWriter, r *http.Request) {
- tchan := Srv.Store.Team().Get(c.Session.TeamId)
-
- post := model.PostFromJson(r.Body)
- if post == nil {
- c.SetInvalidParam("createValetPost", "post")
- return
- }
-
- cchan := Srv.Store.Channel().CheckOpenChannelPermissions(c.Session.TeamId, post.ChannelId)
-
- // Any one with access to the team can post as valet to any open channel
- if !c.HasPermissionsToChannel(cchan, "createValetPost") {
- return
- }
-
- // Make sure this team has the valet feature enabled
- if tResult := <-tchan; tResult.Err != nil {
- c.Err = model.NewAppError("createValetPost", "Could not find the team for this session, team_id="+c.Session.TeamId, "")
- return
- } else {
- if !tResult.Data.(*model.Team).AllowValet {
- c.Err = model.NewAppError("createValetPost", "The valet feature is currently turned off. Please contact your team administrator for details.", "")
- c.Err.StatusCode = http.StatusNotImplemented
- return
- }
- }
-
- if rp, err := CreateValetPost(c, post); err != nil {
- c.Err = err
-
- if strings.Contains(c.Err.Message, "parameter") {
- c.Err.StatusCode = http.StatusBadRequest
- }
-
- return
- } else {
- w.Write([]byte(rp.ToJson()))
- }
-}
-
-func CreateValetPost(c *Context, post *model.Post) (*model.Post, *model.AppError) {
- post.Hashtags, _ = model.ParseHashtags(post.Message)
-
- post.Filenames = []string{} // no files allowed in valet posts yet
-
- if result := <-Srv.Store.User().GetByUsername(c.Session.TeamId, "valet"); result.Err != nil {
- // if the bot doesn't exist, create it
- if tresult := <-Srv.Store.Team().Get(c.Session.TeamId); tresult.Err != nil {
- return nil, tresult.Err
- } else {
- post.UserId = (CreateValet(c, tresult.Data.(*model.Team))).Id
- }
- } else {
- post.UserId = result.Data.(*model.User).Id
- }
-
- var rpost *model.Post
- if result := <-Srv.Store.Post().Save(post); result.Err != nil {
- return nil, result.Err
- } else {
- rpost = result.Data.(*model.Post)
- }
-
- fireAndForgetNotifications(rpost, c.Session.TeamId, c.GetSiteURL())
-
- return rpost, nil
-}
-
func CreatePost(c *Context, post *model.Post, doUpdateLastViewed bool) (*model.Post, *model.AppError) {
var pchan store.StoreChannel
if len(post.RootId) > 0 {
@@ -230,7 +160,7 @@ func fireAndForgetNotifications(post *model.Post, teamId, siteURL string) {
channel = result.Data.(*model.Channel)
if channel.Type == model.CHANNEL_DIRECT {
bodyText = "You have one new message."
- subjectText = "New Private Message"
+ subjectText = "New Direct Message"
} else {
bodyText = "You have one new mention."
subjectText = "New Mention"
diff --git a/api/post_test.go b/api/post_test.go
index 4cccfd62a..358611240 100644
--- a/api/post_test.go
+++ b/api/post_test.go
@@ -123,98 +123,6 @@ func TestCreatePost(t *testing.T) {
}
}
-func TestCreateValetPost(t *testing.T) {
- Setup()
-
- team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
- team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
-
- team2 := &model.Team{DisplayName: "Name Team 2", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
- team2 = Client.Must(Client.CreateTeam(team2)).Data.(*model.Team)
-
- user1 := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
- user1 = Client.Must(Client.CreateUser(user1, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user1.Id))
-
- user2 := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
- user2 = Client.Must(Client.CreateUser(user2, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user2.Id))
-
- Client.LoginByEmail(team.Name, user1.Email, "pwd")
-
- channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
- channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
-
- channel2 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
- channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
-
- if utils.Cfg.TeamSettings.AllowValetDefault {
- post1 := &model.Post{ChannelId: channel1.Id, Message: "#hashtag a" + model.NewId() + "a"}
- rpost1, err := Client.CreateValetPost(post1)
- if err != nil {
- t.Fatal(err)
- }
-
- if rpost1.Data.(*model.Post).Message != post1.Message {
- t.Fatal("message didn't match")
- }
-
- if rpost1.Data.(*model.Post).Hashtags != "#hashtag" {
- t.Fatal("hashtag didn't match")
- }
-
- post2 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a", RootId: rpost1.Data.(*model.Post).Id}
- rpost2, err := Client.CreateValetPost(post2)
- if err != nil {
- t.Fatal(err)
- }
-
- post3 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a", RootId: rpost1.Data.(*model.Post).Id, ParentId: rpost2.Data.(*model.Post).Id}
- _, err = Client.CreateValetPost(post3)
- if err != nil {
- t.Fatal(err)
- }
-
- post4 := &model.Post{ChannelId: "junk", Message: "a" + model.NewId() + "a"}
- _, err = Client.CreateValetPost(post4)
- if err.StatusCode != http.StatusForbidden {
- t.Fatal("Should have been forbidden")
- }
-
- Client.LoginByEmail(team.Name, user2.Email, "pwd")
- post5 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a"}
- _, err = Client.CreateValetPost(post5)
- if err != nil {
- t.Fatal(err)
- }
-
- user3 := &model.User{TeamId: team2.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
- user3 = Client.Must(Client.CreateUser(user3, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user3.Id))
-
- Client.LoginByEmail(team2.Name, user3.Email, "pwd")
-
- channel3 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team2.Id}
- channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel)
-
- post6 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a"}
- _, err = Client.CreateValetPost(post6)
- if err.StatusCode != http.StatusForbidden {
- t.Fatal("Should have been forbidden")
- }
-
- if _, err = Client.DoApiPost("/channels/"+channel3.Id+"/create", "garbage"); err == nil {
- t.Fatal("should have been an error")
- }
- } else {
- post1 := &model.Post{ChannelId: channel1.Id, Message: "#hashtag a" + model.NewId() + "a"}
- _, err := Client.CreateValetPost(post1)
- if err.StatusCode != http.StatusNotImplemented {
- t.Fatal("Should have failed with 501 - Not Implemented")
- }
- }
-}
-
func TestUpdatePost(t *testing.T) {
Setup()
diff --git a/api/server.go b/api/server.go
index 3273e766c..3f23d8df6 100644
--- a/api/server.go
+++ b/api/server.go
@@ -38,11 +38,11 @@ func NewServer() {
func StartServer() {
l4g.Info("Starting Server...")
- l4g.Info("Server is listening on " + utils.Cfg.ServiceSettings.Port)
+ l4g.Info("Server is listening on " + utils.Cfg.ServiceSettings.ListenAddress)
var handler http.Handler = Srv.Router
- if utils.Cfg.RateLimitSettings.UseRateLimiter {
+ if utils.Cfg.RateLimitSettings.EnableRateLimiter {
l4g.Info("RateLimiter is enabled")
vary := throttled.VaryBy{}
@@ -71,7 +71,7 @@ func StartServer() {
}
go func() {
- err := Srv.Server.ListenAndServe(":"+utils.Cfg.ServiceSettings.Port, handler)
+ err := Srv.Server.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handler)
if err != nil {
l4g.Critical("Error starting server, err:%v", err)
time.Sleep(time.Second)
diff --git a/api/team.go b/api/team.go
index 92fcbff93..4794b66df 100644
--- a/api/team.go
+++ b/api/team.go
@@ -25,12 +25,12 @@ func InitTeam(r *mux.Router) {
sr.Handle("/create_from_signup", ApiAppHandler(createTeamFromSignup)).Methods("POST")
sr.Handle("/create_with_sso/{service:[A-Za-z]+}", ApiAppHandler(createTeamFromSSO)).Methods("POST")
sr.Handle("/signup", ApiAppHandler(signupTeam)).Methods("POST")
+ sr.Handle("/all", ApiUserRequired(getAll)).Methods("GET")
sr.Handle("/find_team_by_name", ApiAppHandler(findTeamByName)).Methods("POST")
sr.Handle("/find_teams", ApiAppHandler(findTeams)).Methods("POST")
sr.Handle("/email_teams", ApiAppHandler(emailTeams)).Methods("POST")
sr.Handle("/invite_members", ApiUserRequired(inviteMembers)).Methods("POST")
sr.Handle("/update_name", ApiUserRequired(updateTeamDisplayName)).Methods("POST")
- sr.Handle("/update_valet_feature", ApiUserRequired(updateValetFeature)).Methods("POST")
sr.Handle("/me", ApiUserRequired(getMyTeam)).Methods("GET")
// These should be moved to the global admain console
sr.Handle("/import_team", ApiUserRequired(importTeam)).Methods("POST")
@@ -38,7 +38,7 @@ func InitTeam(r *mux.Router) {
}
func signupTeam(c *Context, w http.ResponseWriter, r *http.Request) {
- if utils.Cfg.ServiceSettings.DisableEmailSignUp {
+ if !utils.Cfg.EmailSettings.EnableSignUpWithEmail {
c.Err = model.NewAppError("signupTeam", "Team sign-up with email is disabled.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
@@ -60,14 +60,13 @@ func signupTeam(c *Context, w http.ResponseWriter, r *http.Request) {
subjectPage.Props["SiteURL"] = c.GetSiteURL()
bodyPage := NewServerTemplatePage("signup_team_body")
bodyPage.Props["SiteURL"] = c.GetSiteURL()
- bodyPage.Props["TourUrl"] = utils.Cfg.TeamSettings.TourLink
props := make(map[string]string)
props["email"] = email
props["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(props)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt))
bodyPage.Props["Link"] = fmt.Sprintf("%s/signup_team_complete/?d=%s&h=%s", c.GetSiteURL(), url.QueryEscape(data), url.QueryEscape(hash))
@@ -76,10 +75,7 @@ func signupTeam(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- if utils.Cfg.ServiceSettings.Mode == utils.MODE_DEV || utils.Cfg.EmailSettings.ByPassEmail {
- m["follow_link"] = bodyPage.Props["Link"]
- }
-
+ m["follow_link"] = bodyPage.Props["Link"]
w.Header().Set("Access-Control-Allow-Origin", " *")
w.Write([]byte(model.MapToJson(m)))
}
@@ -88,7 +84,8 @@ func createTeamFromSSO(c *Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
service := params["service"]
- if !utils.IsServiceAllowed(service) {
+ sso := utils.Cfg.GetSSOService(service)
+ if sso != nil && !sso.Enable {
c.SetInvalidParam("createTeamFromSSO", "service")
return
}
@@ -126,8 +123,6 @@ func createTeamFromSSO(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
- team.AllowValet = utils.Cfg.TeamSettings.AllowValetDefault
-
if result := <-Srv.Store.Team().Save(team); result.Err != nil {
c.Err = result.Err
return
@@ -147,7 +142,7 @@ func createTeamFromSSO(c *Context, w http.ResponseWriter, r *http.Request) {
}
func createTeamFromSignup(c *Context, w http.ResponseWriter, r *http.Request) {
- if utils.Cfg.ServiceSettings.DisableEmailSignUp {
+ if !utils.Cfg.EmailSettings.EnableSignUpWithEmail {
c.Err = model.NewAppError("createTeamFromSignup", "Team sign-up with email is disabled.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
@@ -188,7 +183,7 @@ func createTeamFromSignup(c *Context, w http.ResponseWriter, r *http.Request) {
teamSignup.User.TeamId = ""
teamSignup.User.Password = password
- if !model.ComparePassword(teamSignup.Hash, fmt.Sprintf("%v:%v", teamSignup.Data, utils.Cfg.ServiceSettings.InviteSalt)) {
+ if !model.ComparePassword(teamSignup.Hash, fmt.Sprintf("%v:%v", teamSignup.Data, utils.Cfg.EmailSettings.InviteSalt)) {
c.Err = model.NewAppError("createTeamFromSignup", "The signup link does not appear to be valid", "")
return
}
@@ -209,8 +204,6 @@ func createTeamFromSignup(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- teamSignup.Team.AllowValet = utils.Cfg.TeamSettings.AllowValetDefault
-
if result := <-Srv.Store.Team().Save(&teamSignup.Team); result.Err != nil {
c.Err = result.Err
return
@@ -230,13 +223,6 @@ func createTeamFromSignup(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- if teamSignup.Team.AllowValet {
- CreateValet(c, rteam)
- if c.Err != nil {
- return
- }
- }
-
InviteMembers(c, rteam, ruser, teamSignup.Invites)
teamSignup.Team = *rteam
@@ -257,7 +243,7 @@ func createTeam(c *Context, w http.ResponseWriter, r *http.Request) {
}
func CreateTeam(c *Context, team *model.Team) *model.Team {
- if utils.Cfg.ServiceSettings.DisableEmailSignUp {
+ if !utils.Cfg.EmailSettings.EnableSignUpWithEmail {
c.Err = model.NewAppError("createTeam", "Team sign-up with email is disabled.", "")
c.Err.StatusCode = http.StatusNotImplemented
return nil
@@ -272,11 +258,6 @@ func CreateTeam(c *Context, team *model.Team) *model.Team {
return nil
}
- if utils.Cfg.ServiceSettings.Mode != utils.MODE_DEV {
- c.Err = model.NewAppError("CreateTeam", "The mode does not allow network creation without a valid invite", "")
- return nil
- }
-
if result := <-Srv.Store.Team().Save(team); result.Err != nil {
c.Err = result.Err
return nil
@@ -288,13 +269,6 @@ func CreateTeam(c *Context, team *model.Team) *model.Team {
return nil
}
- if rteam.AllowValet {
- CreateValet(c, rteam)
- if c.Err != nil {
- return nil
- }
- }
-
return rteam
}
}
@@ -303,7 +277,7 @@ func isTreamCreationAllowed(c *Context, email string) bool {
email = strings.ToLower(email)
- if utils.Cfg.TeamSettings.DisableTeamCreation {
+ if !utils.Cfg.TeamSettings.EnableTeamCreation {
c.Err = model.NewAppError("isTreamCreationAllowed", "Team creation has been disabled. Please ask your systems administrator for details.", "")
return false
}
@@ -328,6 +302,53 @@ func isTreamCreationAllowed(c *Context, email string) bool {
return true
}
+func getAll(c *Context, w http.ResponseWriter, r *http.Request) {
+ if !c.HasSystemAdminPermissions("getLogs") {
+ return
+ }
+
+ if result := <-Srv.Store.Team().GetAll(); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ teams := result.Data.([]*model.Team)
+ m := make(map[string]*model.Team)
+ for _, v := range teams {
+ m[v.Id] = v
+ }
+
+ w.Write([]byte(model.TeamMapToJson(m)))
+ }
+}
+
+func revokeAllSessions(c *Context, w http.ResponseWriter, r *http.Request) {
+ props := model.MapFromJson(r.Body)
+ id := props["id"]
+
+ if result := <-Srv.Store.Session().Get(id); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ session := result.Data.(*model.Session)
+
+ c.LogAudit("revoked_all=" + id)
+
+ if session.IsOAuth {
+ RevokeAccessToken(session.Token)
+ } else {
+ sessionCache.Remove(session.Token)
+
+ if result := <-Srv.Store.Session().Remove(session.Id); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ w.Write([]byte(model.MapToJson(props)))
+ return
+ }
+ }
+ }
+}
+
func findTeamByName(c *Context, w http.ResponseWriter, r *http.Request) {
m := model.MapFromJson(r.Body)
@@ -509,10 +530,10 @@ func InviteMembers(c *Context, team *model.Team, user *model.User, invites []str
props["name"] = team.Name
props["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(props)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt))
bodyPage.Props["Link"] = fmt.Sprintf("%s/signup_user_complete/?d=%s&h=%s", c.GetSiteURL(), url.QueryEscape(data), url.QueryEscape(hash))
- if utils.Cfg.ServiceSettings.Mode == utils.MODE_DEV {
+ if !utils.Cfg.EmailSettings.SendEmailNotifications {
l4g.Info("sending invitation to %v %v", invite, bodyPage.Props["Link"])
}
@@ -559,56 +580,6 @@ func updateTeamDisplayName(c *Context, w http.ResponseWriter, r *http.Request) {
w.Write([]byte(model.MapToJson(props)))
}
-func updateValetFeature(c *Context, w http.ResponseWriter, r *http.Request) {
-
- props := model.MapFromJson(r.Body)
-
- allowValetStr := props["allow_valet"]
- if len(allowValetStr) == 0 {
- c.SetInvalidParam("updateValetFeature", "allow_valet")
- return
- }
-
- allowValet := allowValetStr == "true"
-
- teamId := props["team_id"]
- if len(teamId) > 0 && len(teamId) != 26 {
- c.SetInvalidParam("updateValetFeature", "team_id")
- return
- } else if len(teamId) == 0 {
- teamId = c.Session.TeamId
- }
-
- tchan := Srv.Store.Team().Get(teamId)
-
- if !c.HasPermissionsToTeam(teamId, "updateValetFeature") {
- return
- }
-
- if !model.IsInRole(c.Session.Roles, model.ROLE_TEAM_ADMIN) {
- c.Err = model.NewAppError("updateValetFeature", "You do not have the appropriate permissions", "userId="+c.Session.UserId)
- c.Err.StatusCode = http.StatusForbidden
- return
- }
-
- var team *model.Team
- if tResult := <-tchan; tResult.Err != nil {
- c.Err = tResult.Err
- return
- } else {
- team = tResult.Data.(*model.Team)
- }
-
- team.AllowValet = allowValet
-
- if result := <-Srv.Store.Team().Update(team); result.Err != nil {
- c.Err = result.Err
- return
- }
-
- w.Write([]byte(model.MapToJson(props)))
-}
-
func getMyTeam(c *Context, w http.ResponseWriter, r *http.Request) {
if len(c.Session.TeamId) == 0 {
diff --git a/api/team_test.go b/api/team_test.go
index 4f1b9e5f0..e2a7cf430 100644
--- a/api/team_test.go
+++ b/api/team_test.go
@@ -30,7 +30,7 @@ func TestCreateFromSignupTeam(t *testing.T) {
props["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(props)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt))
team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
user := model.User{Email: props["email"], Nickname: "Corey Hulen", Password: "hello"}
@@ -132,6 +132,39 @@ func TestFindTeamByEmail(t *testing.T) {
}
}
+func TestGetAllTeams(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
+ store.Must(Srv.Store.User().VerifyEmail(user.Id))
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ if _, err := Client.GetAllTeams(); err == nil {
+ t.Fatal("you shouldn't have permissions")
+ }
+
+ c := &Context{}
+ c.RequestId = model.NewId()
+ c.IpAddress = "cmd_line"
+ UpdateRoles(c, user, model.ROLE_SYSTEM_ADMIN)
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ if r1, err := Client.GetAllTeams(); err != nil {
+ t.Fatal(err)
+ } else {
+ teams := r1.Data.(map[string]*model.Team)
+ if teams[team.Id].Name != team.Name {
+ t.Fatal()
+ }
+ }
+}
+
/*
XXXXXX investigate and fix failing test
@@ -330,79 +363,3 @@ func TestGetMyTeam(t *testing.T) {
}
}
}
-
-func TestUpdateValetFeature(t *testing.T) {
- Setup()
-
- team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
- team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
-
- user := &model.User{TeamId: team.Id, Email: "test@nowhere.com", Nickname: "Corey Hulen", Password: "pwd"}
- user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user.Id))
-
- user2 := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
- user2 = Client.Must(Client.CreateUser(user2, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user2.Id))
-
- team2 := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
- team2 = Client.Must(Client.CreateTeam(team2)).Data.(*model.Team)
-
- user3 := &model.User{TeamId: team2.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
- user3 = Client.Must(Client.CreateUser(user3, "")).Data.(*model.User)
- store.Must(Srv.Store.User().VerifyEmail(user3.Id))
-
- Client.LoginByEmail(team.Name, user2.Email, "pwd")
-
- data := make(map[string]string)
- data["allow_valet"] = "true"
- if _, err := Client.UpdateValetFeature(data); err == nil {
- t.Fatal("Should have errored, not admin")
- }
-
- Client.LoginByEmail(team.Name, user.Email, "pwd")
-
- data["allow_valet"] = ""
- if _, err := Client.UpdateValetFeature(data); err == nil {
- t.Fatal("Should have errored, empty allow_valet field")
- }
-
- data["allow_valet"] = "true"
- if _, err := Client.UpdateValetFeature(data); err != nil {
- t.Fatal(err)
- }
-
- rteam := Client.Must(Client.GetMyTeam("")).Data.(*model.Team)
- if rteam.AllowValet != true {
- t.Fatal("Should have errored - allow valet property not updated")
- }
-
- data["team_id"] = "junk"
- if _, err := Client.UpdateValetFeature(data); err == nil {
- t.Fatal("Should have errored, junk team id")
- }
-
- data["team_id"] = "12345678901234567890123456"
- if _, err := Client.UpdateValetFeature(data); err == nil {
- t.Fatal("Should have errored, bad team id")
- }
-
- data["team_id"] = team.Id
- data["allow_valet"] = "false"
- if _, err := Client.UpdateValetFeature(data); err != nil {
- t.Fatal(err)
- }
-
- rteam = Client.Must(Client.GetMyTeam("")).Data.(*model.Team)
- if rteam.AllowValet != false {
- t.Fatal("Should have errored - allow valet property not updated")
- }
-
- Client.LoginByEmail(team2.Name, user3.Email, "pwd")
-
- data["team_id"] = team.Id
- data["allow_valet"] = "true"
- if _, err := Client.UpdateValetFeature(data); err == nil {
- t.Fatal("Should have errored, not part of team")
- }
-}
diff --git a/api/templates/error.html b/api/templates/error.html
index 760578896..6b643556e 100644
--- a/api/templates/error.html
+++ b/api/templates/error.html
@@ -23,7 +23,7 @@
<div class="error__container">
<div class="error__icon"><i class="fa fa-exclamation-triangle"></i></div>
<h2>{{ .ClientProps.SiteName }} needs your help:</h2>
- <p>{{.Message}}</p>
+ <p>{{ .Props.Message }}</p>
<a href="{{.Props.SiteURL}}">Go back to team site</a>
</div>
</div>
diff --git a/api/templates/signup_team_body.html b/api/templates/signup_team_body.html
index f5c0e62b0..e6ffb3a5b 100644
--- a/api/templates/signup_team_body.html
+++ b/api/templates/signup_team_body.html
@@ -22,9 +22,6 @@
<a href="{{.Props.Link}}" style="background: #2389D7; border-radius: 3px; color: #fff; border: none; outline: none; min-width: 200px; padding: 15px 25px; font-size: 14px; font-family: inherit; cursor: pointer; -webkit-appearance: none;text-decoration: none;">Set up your team</a>
</p>
{{ .ClientProps.SiteName }} is one place for all your team communication, searchable and available anywhere.<br>You'll get more out of {{ .ClientProps.SiteName }} when your team is in constant communication--let's get them on board.<br></p>
- <p>
- Learn more by <a href="{{.Props.TourUrl}}" style="text-decoration: none; color:#2389D7;">taking a tour</a>
- </p>
</td>
</tr>
<tr>
diff --git a/api/templates/welcome_body.html b/api/templates/welcome_body.html
index c75e14c6a..5fe3450b7 100644
--- a/api/templates/welcome_body.html
+++ b/api/templates/welcome_body.html
@@ -17,15 +17,9 @@
<table border="0" cellpadding="0" cellspacing="0" style="padding: 20px 50px 0; text-align: center; margin: 0 auto">
<tr>
<td style="border-bottom: 1px solid #ddd; padding: 0 0 20px;">
- <h2 style="font-weight: normal; margin-top: 10px;">You joined the {{.Props.TeamDisplayName}} team at {{.ClientProps.SiteName}}!</h2>
- <p>Please let me know if you have any questions.<br>Enjoy your stay at <a href="{{.Props.TeamURL}}">{{.ClientProps.SiteName}}</a>.</p>
- </td>
- </tr>
- <tr>
- <td style="color: #999; padding-top: 20px; line-height: 25px; font-size: 13px;">
- Any questions at all, mail us any time: <a href="mailto:{{.ClientProps.FeedbackEmail}}" style="text-decoration: none; color:#2389D7;">{{.ClientProps.FeedbackEmail}}</a>.<br>
- Best wishes,<br>
- The {{.ClientProps.SiteName}} Team<br>
+ <h2 style="font-weight: normal; margin-top: 10px;">You can sign-in to your new team from the web address:</h2>
+ <a href="{{.Props.TeamURL}}">{{.Props.TeamURL}}</a>
+ <p>Mattermost lets you share messages and files from your PC or phone, with instant search and archiving.</p>
</td>
</tr>
</table>
diff --git a/api/templates/welcome_subject.html b/api/templates/welcome_subject.html
index 2214f7a38..c3b70ef20 100644
--- a/api/templates/welcome_subject.html
+++ b/api/templates/welcome_subject.html
@@ -1 +1 @@
-{{define "welcome_subject"}}Welcome to {{ .ClientProps.SiteName }}{{end}} \ No newline at end of file
+{{define "welcome_subject"}}You joined {{ .Props.TeamDisplayName }}{{end}}
diff --git a/api/user.go b/api/user.go
index 0a54b6a5d..695ab2208 100644
--- a/api/user.go
+++ b/api/user.go
@@ -8,13 +8,13 @@ import (
l4g "code.google.com/p/log4go"
b64 "encoding/base64"
"fmt"
+ "github.com/disintegration/imaging"
"github.com/golang/freetype"
"github.com/gorilla/mux"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
"github.com/mssola/user_agent"
- "github.com/nfnt/resize"
"hash/fnv"
"image"
"image/color"
@@ -51,6 +51,7 @@ func InitUser(r *mux.Router) {
sr.Handle("/me", ApiAppHandler(getMe)).Methods("GET")
sr.Handle("/status", ApiUserRequiredActivity(getStatuses, false)).Methods("GET")
sr.Handle("/profiles", ApiUserRequired(getProfiles)).Methods("GET")
+ sr.Handle("/profiles/{id:[A-Za-z0-9]+}", ApiUserRequired(getProfiles)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}", ApiUserRequired(getUser)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}/sessions", ApiUserRequired(getSessions)).Methods("GET")
sr.Handle("/{id:[A-Za-z0-9]+}/audits", ApiUserRequired(getAudits)).Methods("GET")
@@ -58,7 +59,7 @@ func InitUser(r *mux.Router) {
}
func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
- if utils.Cfg.ServiceSettings.DisableEmailSignUp {
+ if !utils.Cfg.EmailSettings.EnableSignUpWithEmail {
c.Err = model.NewAppError("signupTeam", "User sign-up with email is disabled.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
@@ -90,7 +91,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
data := r.URL.Query().Get("d")
props := model.MapFromJson(strings.NewReader(data))
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) {
c.Err = model.NewAppError("createUser", "The signup link does not appear to be valid", "")
return
}
@@ -155,31 +156,35 @@ func IsVerifyHashRequired(user *model.User, team *model.Team, hash string) bool
return shouldVerifyHash
}
-func CreateValet(c *Context, team *model.Team) *model.User {
- valet := &model.User{}
- valet.TeamId = team.Id
- valet.Email = utils.Cfg.EmailSettings.FeedbackEmail
- valet.EmailVerified = true
- valet.Username = model.BOT_USERNAME
- valet.Password = model.NewId()
-
- return CreateUser(c, team, valet)
-}
-
func CreateUser(c *Context, team *model.Team, user *model.User) *model.User {
+ if !utils.Cfg.TeamSettings.EnableUserCreation {
+ c.Err = model.NewAppError("CreateUser", "User creation has been disabled. Please ask your systems administrator for details.", "")
+ return nil
+ }
+
channelRole := ""
if team.Email == user.Email {
user.Roles = model.ROLE_TEAM_ADMIN
channelRole = model.CHANNEL_ROLE_ADMIN
+
+ // Below is a speical case where the first user in the entire
+ // system is granted the system_admin role instead of admin
+ if result := <-Srv.Store.User().GetTotalUsersCount(); result.Err != nil {
+ c.Err = result.Err
+ return nil
+ } else {
+ count := result.Data.(int64)
+ if count <= 0 {
+ user.Roles = model.ROLE_SYSTEM_ADMIN
+ }
+ }
+
} else {
user.Roles = ""
}
user.MakeNonNil()
- if len(user.Props["theme"]) == 0 {
- user.AddProp("theme", utils.Cfg.TeamSettings.DefaultThemeColor)
- }
if result := <-Srv.Store.User().Save(user); result.Err != nil {
c.Err = result.Err
@@ -193,7 +198,7 @@ func CreateUser(c *Context, team *model.Team, user *model.User) *model.User {
l4g.Error("Encountered an issue joining default channels user_id=%s, team_id=%s, err=%v", ruser.Id, ruser.TeamId, err)
}
- //fireAndForgetWelcomeEmail(ruser.FirstName, ruser.Email, team.Name, c.TeamURL+"/channels/town-square")
+ fireAndForgetWelcomeEmail(ruser.Email, team.DisplayName, c.GetTeamURLFromTeam(team))
if user.EmailVerified {
if cresult := <-Srv.Store.User().VerifyEmail(ruser.Id); cresult.Err != nil {
l4g.Error("Failed to set email verified err=%v", cresult.Err)
@@ -213,17 +218,13 @@ func CreateUser(c *Context, team *model.Team, user *model.User) *model.User {
}
}
-func fireAndForgetWelcomeEmail(name, email, teamDisplayName, link, siteURL string) {
+func fireAndForgetWelcomeEmail(email, teamDisplayName, teamURL string) {
go func() {
subjectPage := NewServerTemplatePage("welcome_subject")
- subjectPage.Props["SiteURL"] = siteURL
+ subjectPage.Props["TeamDisplayName"] = teamDisplayName
bodyPage := NewServerTemplatePage("welcome_body")
- bodyPage.Props["SiteURL"] = siteURL
- bodyPage.Props["Nickname"] = name
- bodyPage.Props["TeamDisplayName"] = teamDisplayName
- bodyPage.Props["FeedbackName"] = utils.Cfg.EmailSettings.FeedbackName
- bodyPage.Props["TeamURL"] = link
+ bodyPage.Props["TeamURL"] = teamURL
if err := utils.SendMail(email, subjectPage.Render(), bodyPage.Render()); err != nil {
l4g.Error("Failed to send welcome email successfully err=%v", err)
@@ -293,7 +294,7 @@ func LoginByEmail(c *Context, w http.ResponseWriter, r *http.Request, email, nam
func checkUserPassword(c *Context, user *model.User, password string) bool {
- if user.FailedAttempts >= utils.Cfg.ServiceSettings.AllowedLoginAttempts {
+ if user.FailedAttempts >= utils.Cfg.ServiceSettings.MaximumLoginAttempts {
c.LogAuditWithUserId(user.Id, "fail")
c.Err = model.NewAppError("checkUserPassword", "Your account is locked because of too many failed password attempts. Please reset your password.", "user_id="+user.Id)
c.Err.StatusCode = http.StatusForbidden
@@ -324,7 +325,7 @@ func checkUserPassword(c *Context, user *model.User, password string) bool {
func Login(c *Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) {
c.LogAuditWithUserId(user.Id, "attempt")
- if !user.EmailVerified && !utils.Cfg.EmailSettings.ByPassEmail {
+ if !user.EmailVerified && utils.Cfg.EmailSettings.RequireEmailVerification {
c.Err = model.NewAppError("Login", "Login failed because email address has not been verified", "user_id="+user.Id)
c.Err.StatusCode = http.StatusForbidden
return
@@ -559,13 +560,26 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) {
}
func getProfiles(c *Context, w http.ResponseWriter, r *http.Request) {
+ params := mux.Vars(r)
+ id, ok := params["id"]
+ if ok {
+ // You must be system admin to access another team
+ if id != c.Session.TeamId {
+ if !c.HasSystemAdminPermissions("getProfiles") {
+ return
+ }
+ }
+
+ } else {
+ id = c.Session.TeamId
+ }
- etag := (<-Srv.Store.User().GetEtagForProfiles(c.Session.TeamId)).Data.(string)
+ etag := (<-Srv.Store.User().GetEtagForProfiles(id)).Data.(string)
if HandleEtag(etag, w, r) {
return
}
- if result := <-Srv.Store.User().GetProfiles(c.Session.TeamId); result.Err != nil {
+ if result := <-Srv.Store.User().GetProfiles(id); result.Err != nil {
c.Err = result.Err
return
} else {
@@ -655,7 +669,7 @@ func createProfileImage(username string, userId string) ([]byte, *model.AppError
initial := string(strings.ToUpper(username)[0])
- fontBytes, err := ioutil.ReadFile(utils.FindDir("web/static/fonts") + utils.Cfg.ImageSettings.InitialFont)
+ fontBytes, err := ioutil.ReadFile(utils.FindDir("web/static/fonts") + utils.Cfg.FileSettings.InitialFont)
if err != nil {
return nil, model.NewAppError("createProfileImage", "Could not create default profile image font", err.Error())
}
@@ -664,8 +678,8 @@ func createProfileImage(username string, userId string) ([]byte, *model.AppError
return nil, model.NewAppError("createProfileImage", "Could not create default profile image font", err.Error())
}
- width := int(utils.Cfg.ImageSettings.ProfileWidth)
- height := int(utils.Cfg.ImageSettings.ProfileHeight)
+ width := int(utils.Cfg.FileSettings.ProfileWidth)
+ height := int(utils.Cfg.FileSettings.ProfileHeight)
color := colors[int64(seed)%int64(len(colors))]
dstImg := image.NewRGBA(image.Rect(0, 0, width, height))
srcImg := image.White
@@ -704,7 +718,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
} else {
var img []byte
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
var err *model.AppError
if img, err = createProfileImage(result.Data.(*model.User).Username, id); err != nil {
c.Err = err
@@ -741,8 +755,8 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
}
func uploadProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
- if !utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
- c.Err = model.NewAppError("uploadProfileImage", "Unable to upload file. Amazon S3 not configured and local server storage turned off. ", "")
+ if len(utils.Cfg.FileSettings.DriverName) == 0 {
+ c.Err = model.NewAppError("uploadProfileImage", "Unable to upload file. Image storage is not configured.", "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
@@ -784,7 +798,7 @@ func uploadProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
}
// Scale profile image
- img = resize.Resize(utils.Cfg.ImageSettings.ProfileWidth, utils.Cfg.ImageSettings.ProfileHeight, img, resize.Lanczos3)
+ img = imaging.Resize(img, utils.Cfg.FileSettings.ProfileWidth, utils.Cfg.FileSettings.ProfileHeight, imaging.Lanczos)
buf := new(bytes.Buffer)
err = png.Encode(buf, img)
@@ -803,6 +817,9 @@ func uploadProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
Srv.Store.User().UpdateLastPictureUpdate(c.Session.UserId)
c.LogAudit("")
+
+ // write something as the response since jQuery expects a json response
+ w.Write([]byte("true"))
}
func updateUser(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -933,8 +950,8 @@ func updateRoles(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- if model.IsInRole(new_roles, model.ROLE_SYSTEM_ADMIN) {
- c.Err = model.NewAppError("updateRoles", "The system_admin role can only be set from the command line", "")
+ if model.IsInRole(new_roles, model.ROLE_SYSTEM_ADMIN) && !c.IsSystemAdmin() {
+ c.Err = model.NewAppError("updateRoles", "The system_admin role can only be set by another system admin", "")
c.Err.StatusCode = http.StatusForbidden
return
}
@@ -1135,7 +1152,7 @@ func sendPasswordReset(c *Context, w http.ResponseWriter, r *http.Request) {
newProps["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(newProps)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.ResetSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.PasswordResetSalt))
link := fmt.Sprintf("%s/reset_password?d=%s&h=%s", c.GetTeamURLFromTeam(team), url.QueryEscape(data), url.QueryEscape(hash))
@@ -1164,29 +1181,35 @@ func resetPassword(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- hash := props["hash"]
- if len(hash) == 0 {
- c.SetInvalidParam("resetPassword", "hash")
+ name := props["name"]
+ if len(name) == 0 {
+ c.SetInvalidParam("resetPassword", "name")
return
}
- data := model.MapFromJson(strings.NewReader(props["data"]))
+ userId := props["user_id"]
+ hash := props["hash"]
+ timeStr := ""
- userId := data["user_id"]
- if len(userId) != 26 {
- c.SetInvalidParam("resetPassword", "data:user_id")
- return
- }
+ if !c.IsSystemAdmin() {
+ if len(hash) == 0 {
+ c.SetInvalidParam("resetPassword", "hash")
+ return
+ }
- timeStr := data["time"]
- if len(timeStr) == 0 {
- c.SetInvalidParam("resetPassword", "data:time")
- return
+ data := model.MapFromJson(strings.NewReader(props["data"]))
+
+ userId = data["user_id"]
+
+ timeStr = data["time"]
+ if len(timeStr) == 0 {
+ c.SetInvalidParam("resetPassword", "data:time")
+ return
+ }
}
- name := props["name"]
- if len(name) == 0 {
- c.SetInvalidParam("resetPassword", "name")
+ if len(userId) != 26 {
+ c.SetInvalidParam("resetPassword", "user_id")
return
}
@@ -1214,15 +1237,17 @@ func resetPassword(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", props["data"], utils.Cfg.ServiceSettings.ResetSalt)) {
- c.Err = model.NewAppError("resetPassword", "The reset password link does not appear to be valid", "")
- return
- }
+ if !c.IsSystemAdmin() {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", props["data"], utils.Cfg.EmailSettings.PasswordResetSalt)) {
+ c.Err = model.NewAppError("resetPassword", "The reset password link does not appear to be valid", "")
+ return
+ }
- t, err := strconv.ParseInt(timeStr, 10, 64)
- if err != nil || model.GetMillis()-t > 1000*60*60 { // one hour
- c.Err = model.NewAppError("resetPassword", "The reset link has expired", "")
- return
+ t, err := strconv.ParseInt(timeStr, 10, 64)
+ if err != nil || model.GetMillis()-t > 1000*60*60 { // one hour
+ c.Err = model.NewAppError("resetPassword", "The reset link has expired", "")
+ return
+ }
}
if result := <-Srv.Store.User().UpdatePassword(userId, model.HashPassword(newPassword)); result.Err != nil {
@@ -1362,15 +1387,16 @@ func getStatuses(c *Context, w http.ResponseWriter, r *http.Request) {
func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, teamName, service, redirectUri, loginHint string) {
- if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow {
+ sso := utils.Cfg.GetSSOService(service)
+ if sso != nil && !sso.Enable {
c.Err = model.NewAppError("GetAuthorizationCode", "Unsupported OAuth service provider", "service="+service)
c.Err.StatusCode = http.StatusBadRequest
return
}
- clientId := utils.Cfg.SSOSettings[service].Id
- endpoint := utils.Cfg.SSOSettings[service].AuthEndpoint
- scope := utils.Cfg.SSOSettings[service].Scope
+ clientId := sso.Id
+ endpoint := sso.AuthEndpoint
+ scope := sso.Scope
stateProps := map[string]string{"team": teamName, "hash": model.HashPassword(clientId)}
state := b64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
@@ -1389,7 +1415,8 @@ func GetAuthorizationCode(c *Context, w http.ResponseWriter, r *http.Request, te
}
func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser, *model.Team, *model.AppError) {
- if s, ok := utils.Cfg.SSOSettings[service]; !ok || !s.Allow {
+ sso := utils.Cfg.GetSSOService(service)
+ if sso != nil && !sso.Enable {
return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Unsupported OAuth service provider", "service="+service)
}
@@ -1402,7 +1429,7 @@ func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser
stateProps := model.MapFromJson(strings.NewReader(stateStr))
- if !model.ComparePassword(stateProps["hash"], utils.Cfg.SSOSettings[service].Id) {
+ if !model.ComparePassword(stateProps["hash"], sso.Id) {
return nil, nil, model.NewAppError("AuthorizeOAuthUser", "Invalid state", "")
}
@@ -1414,14 +1441,14 @@ func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser
tchan := Srv.Store.Team().GetByName(teamName)
p := url.Values{}
- p.Set("client_id", utils.Cfg.SSOSettings[service].Id)
- p.Set("client_secret", utils.Cfg.SSOSettings[service].Secret)
+ p.Set("client_id", sso.Id)
+ p.Set("client_secret", sso.Secret)
p.Set("code", code)
p.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE)
p.Set("redirect_uri", redirectUri)
client := &http.Client{}
- req, _ := http.NewRequest("POST", utils.Cfg.SSOSettings[service].TokenEndpoint, strings.NewReader(p.Encode()))
+ req, _ := http.NewRequest("POST", sso.TokenEndpoint, strings.NewReader(p.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
@@ -1443,7 +1470,7 @@ func AuthorizeOAuthUser(service, code, state, redirectUri string) (io.ReadCloser
p = url.Values{}
p.Set("access_token", ar.AccessToken)
- req, _ = http.NewRequest("GET", utils.Cfg.SSOSettings[service].UserApiEndpoint, strings.NewReader(""))
+ req, _ = http.NewRequest("GET", sso.UserApiEndpoint, strings.NewReader(""))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
diff --git a/api/user_test.go b/api/user_test.go
index 986365bd0..baa567dec 100644
--- a/api/user_test.go
+++ b/api/user_test.go
@@ -151,7 +151,7 @@ func TestLogin(t *testing.T) {
props["display_name"] = rteam2.Data.(*model.Team).DisplayName
props["time"] = fmt.Sprintf("%v", model.GetMillis())
data := model.MapToJson(props)
- hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt))
+ hash := model.HashPassword(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt))
ruser2, _ := Client.CreateUserFromSignup(&user2, data, hash)
@@ -228,6 +228,13 @@ func TestGetUser(t *testing.T) {
ruser2, _ := Client.CreateUser(&user2, "")
store.Must(Srv.Store.User().VerifyEmail(ruser2.Data.(*model.User).Id))
+ team2 := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ rteam2, _ := Client.CreateTeam(&team2)
+
+ user3 := model.User{TeamId: rteam2.Data.(*model.Team).Id, Email: strings.ToLower(model.NewId()) + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ ruser3, _ := Client.CreateUser(&user3, "")
+ store.Must(Srv.Store.User().VerifyEmail(ruser3.Data.(*model.User).Id))
+
Client.LoginByEmail(team.Name, user.Email, user.Password)
rId := ruser.Data.(*model.User).Id
@@ -276,13 +283,27 @@ func TestGetUser(t *testing.T) {
t.Log(cache_result.Data)
t.Fatal("cache should be empty")
}
+ }
+ if _, err := Client.GetProfiles(rteam2.Data.(*model.Team).Id, ""); err == nil {
+ t.Fatal("shouldn't have access")
}
Client.AuthToken = ""
if _, err := Client.GetUser(ruser2.Data.(*model.User).Id, ""); err == nil {
t.Fatal("shouldn't have accss")
}
+
+ c := &Context{}
+ c.RequestId = model.NewId()
+ c.IpAddress = "cmd_line"
+ UpdateRoles(c, ruser.Data.(*model.User), model.ROLE_SYSTEM_ADMIN)
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ if _, err := Client.GetProfiles(rteam2.Data.(*model.Team).Id, ""); err != nil {
+ t.Fatal(err)
+ }
}
func TestGetAudits(t *testing.T) {
@@ -352,19 +373,19 @@ func TestUserCreateImage(t *testing.T) {
Client.DoApiGet("/users/"+user.Id+"/image", "", "")
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
if err := bucket.Del("teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"); err != nil {
t.Fatal(err)
}
} else {
- path := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"
+ path := utils.Cfg.FileSettings.Directory + "teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
@@ -382,7 +403,7 @@ func TestUserUploadProfileImage(t *testing.T) {
user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
store.Must(Srv.Store.User().VerifyEmail(user.Id))
- if utils.IsS3Configured() || utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName != "" {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
@@ -450,19 +471,19 @@ func TestUserUploadProfileImage(t *testing.T) {
Client.DoApiGet("/users/"+user.Id+"/image", "", "")
- if utils.IsS3Configured() && !utils.Cfg.ServiceSettings.UseLocalStorage {
+ if utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
var auth aws.Auth
- auth.AccessKey = utils.Cfg.AWSSettings.S3AccessKeyId
- auth.SecretKey = utils.Cfg.AWSSettings.S3SecretAccessKey
+ auth.AccessKey = utils.Cfg.FileSettings.AmazonS3AccessKeyId
+ auth.SecretKey = utils.Cfg.FileSettings.AmazonS3SecretAccessKey
- s := s3.New(auth, aws.Regions[utils.Cfg.AWSSettings.S3Region])
- bucket := s.Bucket(utils.Cfg.AWSSettings.S3Bucket)
+ s := s3.New(auth, aws.Regions[utils.Cfg.FileSettings.AmazonS3Region])
+ bucket := s.Bucket(utils.Cfg.FileSettings.AmazonS3Bucket)
if err := bucket.Del("teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"); err != nil {
t.Fatal(err)
}
} else {
- path := utils.Cfg.ServiceSettings.StorageDirectory + "teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"
+ path := utils.Cfg.FileSettings.Directory + "teams/" + user.TeamId + "/users/" + user.Id + "/profile.png"
if err := os.Remove(path); err != nil {
t.Fatal("Couldn't remove file at " + path)
}
@@ -814,7 +835,7 @@ func TestResetPassword(t *testing.T) {
props["user_id"] = user.Id
props["time"] = fmt.Sprintf("%v", model.GetMillis())
data["data"] = model.MapToJson(props)
- data["hash"] = model.HashPassword(fmt.Sprintf("%v:%v", data["data"], utils.Cfg.ServiceSettings.ResetSalt))
+ data["hash"] = model.HashPassword(fmt.Sprintf("%v:%v", data["data"], utils.Cfg.EmailSettings.PasswordResetSalt))
data["name"] = team.Name
if _, err := Client.ResetPassword(data); err != nil {
@@ -952,6 +973,7 @@ func TestUserUpdateNotify(t *testing.T) {
}
func TestFuzzyUserCreate(t *testing.T) {
+ Setup()
team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
rteam, _ := Client.CreateTeam(&team)
diff --git a/api/web_socket_test.go b/api/web_socket_test.go
index 161274ff7..49a4c6870 100644
--- a/api/web_socket_test.go
+++ b/api/web_socket_test.go
@@ -16,7 +16,7 @@ import (
func TestSocket(t *testing.T) {
Setup()
- url := "ws://localhost:" + utils.Cfg.ServiceSettings.Port + "/api/v1/websocket"
+ url := "ws://localhost" + utils.Cfg.ServiceSettings.ListenAddress + "/api/v1/websocket"
team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
@@ -116,12 +116,3 @@ func TestSocket(t *testing.T) {
time.Sleep(2 * time.Second)
}
-
-func TestZZWebSocketTearDown(t *testing.T) {
- // *IMPORTANT* - Kind of hacky
- // This should be the last function in any test file
- // that calls Setup()
- // Should be in the last file too sorted by name
- time.Sleep(2 * time.Second)
- TearDown()
-}
diff --git a/api/webhook.go b/api/webhook.go
new file mode 100644
index 000000000..b67655ff5
--- /dev/null
+++ b/api/webhook.go
@@ -0,0 +1,119 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package api
+
+import (
+ l4g "code.google.com/p/log4go"
+ "github.com/gorilla/mux"
+ "github.com/mattermost/platform/model"
+ "github.com/mattermost/platform/utils"
+ "net/http"
+)
+
+func InitWebhook(r *mux.Router) {
+ l4g.Debug("Initializing webhook api routes")
+
+ sr := r.PathPrefix("/hooks").Subrouter()
+ sr.Handle("/incoming/create", ApiUserRequired(createIncomingHook)).Methods("POST")
+ sr.Handle("/incoming/delete", ApiUserRequired(deleteIncomingHook)).Methods("POST")
+ sr.Handle("/incoming/list", ApiUserRequired(getIncomingHooks)).Methods("GET")
+}
+
+func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) {
+ if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ c.Err = model.NewAppError("createIncomingHook", "Incoming webhooks have been disabled by the system admin.", "")
+ c.Err.StatusCode = http.StatusNotImplemented
+ return
+ }
+
+ c.LogAudit("attempt")
+
+ hook := model.IncomingWebhookFromJson(r.Body)
+
+ if hook == nil {
+ c.SetInvalidParam("createIncomingHook", "webhook")
+ return
+ }
+
+ cchan := Srv.Store.Channel().Get(hook.ChannelId)
+ pchan := Srv.Store.Channel().CheckPermissionsTo(c.Session.TeamId, hook.ChannelId, c.Session.UserId)
+
+ hook.UserId = c.Session.UserId
+ hook.TeamId = c.Session.TeamId
+
+ var channel *model.Channel
+ if result := <-cchan; result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ channel = result.Data.(*model.Channel)
+ }
+
+ if !c.HasPermissionsToChannel(pchan, "createIncomingHook") && channel.Type != model.CHANNEL_OPEN {
+ c.LogAudit("fail - bad channel permissions")
+ return
+ }
+
+ if result := <-Srv.Store.Webhook().SaveIncoming(hook); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ c.LogAudit("success")
+ rhook := result.Data.(*model.IncomingWebhook)
+ w.Write([]byte(rhook.ToJson()))
+ }
+}
+
+func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) {
+ if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ c.Err = model.NewAppError("createIncomingHook", "Incoming webhooks have been disabled by the system admin.", "")
+ c.Err.StatusCode = http.StatusNotImplemented
+ return
+ }
+
+ c.LogAudit("attempt")
+
+ props := model.MapFromJson(r.Body)
+
+ id := props["id"]
+ if len(id) == 0 {
+ c.SetInvalidParam("deleteIncomingHook", "id")
+ return
+ }
+
+ if result := <-Srv.Store.Webhook().GetIncoming(id); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ if c.Session.UserId != result.Data.(*model.IncomingWebhook).UserId && !model.IsInRole(c.Session.Roles, model.ROLE_TEAM_ADMIN) {
+ c.LogAudit("fail - inappropriate conditions")
+ c.Err = model.NewAppError("deleteIncomingHook", "Inappropriate permissions to delete incoming webhook", "user_id="+c.Session.UserId)
+ return
+ }
+ }
+
+ if err := (<-Srv.Store.Webhook().DeleteIncoming(id, model.GetMillis())).Err; err != nil {
+ c.Err = err
+ return
+ }
+
+ c.LogAudit("success")
+ w.Write([]byte(model.MapToJson(props)))
+}
+
+func getIncomingHooks(c *Context, w http.ResponseWriter, r *http.Request) {
+ if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ c.Err = model.NewAppError("createIncomingHook", "Incoming webhooks have been disabled by the system admin.", "")
+ c.Err.StatusCode = http.StatusNotImplemented
+ return
+ }
+
+ if result := <-Srv.Store.Webhook().GetIncomingByUser(c.Session.UserId); result.Err != nil {
+ c.Err = result.Err
+ return
+ } else {
+ hooks := result.Data.([]*model.IncomingWebhook)
+ w.Write([]byte(model.IncomingWebhookListToJson(hooks)))
+ }
+}
diff --git a/api/webhook_test.go b/api/webhook_test.go
new file mode 100644
index 000000000..22883f8ca
--- /dev/null
+++ b/api/webhook_test.go
@@ -0,0 +1,162 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package api
+
+import (
+ "github.com/mattermost/platform/model"
+ "github.com/mattermost/platform/store"
+ "github.com/mattermost/platform/utils"
+ "testing"
+ "time"
+)
+
+func TestCreateIncomingHook(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
+ store.Must(Srv.Store.User().VerifyEmail(user.Id))
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
+ channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
+
+ channel2 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
+ channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
+
+ hook := &model.IncomingWebhook{ChannelId: channel1.Id}
+
+ if utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ var rhook *model.IncomingWebhook
+ if result, err := Client.CreateIncomingWebhook(hook); err != nil {
+ t.Fatal(err)
+ } else {
+ rhook = result.Data.(*model.IncomingWebhook)
+ }
+
+ if hook.ChannelId != rhook.ChannelId {
+ t.Fatal("channel ids didn't match")
+ }
+
+ if rhook.UserId != user.Id {
+ t.Fatal("user ids didn't match")
+ }
+
+ if rhook.TeamId != team.Id {
+ t.Fatal("team ids didn't match")
+ }
+
+ hook = &model.IncomingWebhook{ChannelId: "junk"}
+ if _, err := Client.CreateIncomingWebhook(hook); err == nil {
+ t.Fatal("should have failed - bad channel id")
+ }
+
+ hook = &model.IncomingWebhook{ChannelId: channel2.Id, UserId: "123", TeamId: "456"}
+ if result, err := Client.CreateIncomingWebhook(hook); err != nil {
+ t.Fatal(err)
+ } else {
+ if result.Data.(*model.IncomingWebhook).UserId != user.Id {
+ t.Fatal("bad user id wasn't overwritten")
+ }
+ if result.Data.(*model.IncomingWebhook).TeamId != team.Id {
+ t.Fatal("bad team id wasn't overwritten")
+ }
+ }
+ } else {
+ if _, err := Client.CreateIncomingWebhook(hook); err == nil {
+ t.Fatal("should have errored - webhooks turned off")
+ }
+ }
+}
+
+func TestListIncomingHooks(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
+ store.Must(Srv.Store.User().VerifyEmail(user.Id))
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
+ channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
+
+ if utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ hook1 := &model.IncomingWebhook{ChannelId: channel1.Id}
+ hook1 = Client.Must(Client.CreateIncomingWebhook(hook1)).Data.(*model.IncomingWebhook)
+
+ hook2 := &model.IncomingWebhook{ChannelId: channel1.Id}
+ hook2 = Client.Must(Client.CreateIncomingWebhook(hook2)).Data.(*model.IncomingWebhook)
+
+ if result, err := Client.ListIncomingWebhooks(); err != nil {
+ t.Fatal(err)
+ } else {
+ hooks := result.Data.([]*model.IncomingWebhook)
+
+ if len(hooks) != 2 {
+ t.Fatal("incorrect number of hooks")
+ }
+ }
+ } else {
+ if _, err := Client.ListIncomingWebhooks(); err == nil {
+ t.Fatal("should have errored - webhooks turned off")
+ }
+ }
+}
+
+func TestDeleteIncomingHook(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
+ store.Must(Srv.Store.User().VerifyEmail(user.Id))
+
+ Client.LoginByEmail(team.Name, user.Email, "pwd")
+
+ channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
+ channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
+
+ if utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ hook := &model.IncomingWebhook{ChannelId: channel1.Id}
+ hook = Client.Must(Client.CreateIncomingWebhook(hook)).Data.(*model.IncomingWebhook)
+
+ data := make(map[string]string)
+ data["id"] = hook.Id
+
+ if _, err := Client.DeleteIncomingWebhook(data); err != nil {
+ t.Fatal(err)
+ }
+
+ hooks := Client.Must(Client.ListIncomingWebhooks()).Data.([]*model.IncomingWebhook)
+ if len(hooks) != 0 {
+ t.Fatal("delete didn't work properly")
+ }
+ } else {
+ data := make(map[string]string)
+ data["id"] = "123"
+
+ if _, err := Client.DeleteIncomingWebhook(data); err == nil {
+ t.Fatal("should have errored - webhooks turned off")
+ }
+ }
+}
+
+func TestZZWebSocketTearDown(t *testing.T) {
+ // *IMPORTANT* - Kind of hacky
+ // This should be the last function in any test file
+ // that calls Setup()
+ // Should be in the last file too sorted by name
+ time.Sleep(2 * time.Second)
+ TearDown()
+}
diff --git a/config/config.json b/config/config.json
index 38948641c..60e197154 100644
--- a/config/config.json
+++ b/config/config.json
@@ -1,70 +1,73 @@
{
- "LogSettings": {
- "ConsoleEnable": true,
- "ConsoleLevel": "DEBUG",
- "FileEnable": true,
- "FileLevel": "INFO",
- "FileFormat": "",
- "FileLocation": ""
- },
"ServiceSettings": {
+ "ListenAddress": ":8065",
+ "MaximumLoginAttempts": 10,
+ "SegmentDeveloperKey": "",
+ "GoogleDeveloperKey": "",
+ "EnableOAuthServiceProvider": false,
+ "EnableIncomingWebhooks": false,
+ "EnableTesting": false
+ },
+ "TeamSettings": {
"SiteName": "Mattermost",
- "Mode": "dev",
- "AllowTesting": false,
- "UseSSL": false,
- "Port": "8065",
- "Version": "developer",
- "InviteSalt": "gxHVDcKUyP2y1eiyW8S8na1UYQAfq6J6",
- "PublicLinkSalt": "TO3pTyXIZzwHiwyZgGql7lM7DG3zeId4",
- "ResetSalt": "IPxFzSfnDFsNsRafZxz8NaYqFKhf9y2t",
- "AnalyticsUrl": "",
- "UseLocalStorage": true,
- "StorageDirectory": "./data/",
- "AllowedLoginAttempts": 10,
- "DisableEmailSignUp": false,
- "EnableOAuthServiceProvider": false
+ "MaxUsersPerTeam": 50,
+ "EnableTeamCreation": true,
+ "EnableUserCreation": true,
+ "RestrictCreationToDomains": ""
},
"SqlSettings": {
"DriverName": "mysql",
"DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8",
- "DataSourceReplicas": [
- "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8"
- ],
+ "DataSourceReplicas": [],
"MaxIdleConns": 10,
"MaxOpenConns": 10,
"Trace": false,
- "AtRestEncryptKey": "Ya0xMrybACJ3sZZVWQC7e31h5nSDWZFS"
+ "AtRestEncryptKey": "7rAh6iwQCkV4cA1Gsg3fgGOXJAQ43QVg"
},
- "AWSSettings": {
- "S3AccessKeyId": "",
- "S3SecretAccessKey": "",
- "S3Bucket": "",
- "S3Region": ""
+ "LogSettings": {
+ "EnableConsole": true,
+ "ConsoleLevel": "DEBUG",
+ "EnableFile": true,
+ "FileLevel": "INFO",
+ "FileFormat": "",
+ "FileLocation": ""
},
- "ImageSettings": {
+ "FileSettings": {
+ "DriverName": "local",
+ "Directory": "./data/",
+ "EnablePublicLink": true,
+ "PublicLinkSalt": "A705AklYF8MFDOfcwh3I488G8vtLlVip",
"ThumbnailWidth": 120,
"ThumbnailHeight": 100,
"PreviewWidth": 1024,
"PreviewHeight": 0,
"ProfileWidth": 128,
"ProfileHeight": 128,
- "InitialFont": "luximbi.ttf"
+ "InitialFont": "luximbi.ttf",
+ "AmazonS3AccessKeyId": "",
+ "AmazonS3SecretAccessKey": "",
+ "AmazonS3Bucket": "",
+ "AmazonS3Region": ""
},
"EmailSettings": {
- "ByPassEmail": true,
+ "EnableSignUpWithEmail": true,
+ "SendEmailNotifications": false,
+ "RequireEmailVerification": false,
+ "FeedbackName": "",
+ "FeedbackEmail": "",
"SMTPUsername": "",
"SMTPPassword": "",
"SMTPServer": "",
- "UseTLS": false,
- "UseStartTLS": false,
- "FeedbackEmail": "",
- "FeedbackName": "",
+ "SMTPPort": "",
+ "ConnectionSecurity": "",
+ "InviteSalt": "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9YoS",
+ "PasswordResetSalt": "vZ4DcKyVVRlKHHJpexcuXzojkE5PZ5eL",
"ApplePushServer": "",
"ApplePushCertPublic": "",
"ApplePushCertPrivate": ""
},
"RateLimitSettings": {
- "UseRateLimiter": true,
+ "EnableRateLimiter": true,
"PerSec": 10,
"MemoryStoreSize": 10000,
"VaryByRemoteAddr": true,
@@ -72,32 +75,15 @@
},
"PrivacySettings": {
"ShowEmailAddress": true,
- "ShowPhoneNumber": true,
- "ShowSkypeId": true,
"ShowFullName": true
},
- "ClientSettings": {
- "SegmentDeveloperKey": "",
- "GoogleDeveloperKey": ""
- },
- "TeamSettings": {
- "MaxUsersPerTeam": 150,
- "AllowPublicLink": true,
- "AllowValetDefault": false,
- "TourLink": "",
- "DefaultThemeColor": "#2389D7",
- "DisableTeamCreation": false,
- "RestrictCreationToDomains": ""
- },
- "SSOSettings": {
- "gitlab": {
- "Allow": false,
- "Secret": "",
- "Id": "",
- "Scope": "",
- "AuthEndpoint": "",
- "TokenEndpoint": "",
- "UserApiEndpoint": ""
- }
+ "GitLabSettings": {
+ "Enable": false,
+ "Secret": "",
+ "Id": "",
+ "Scope": "",
+ "AuthEndpoint": "",
+ "TokenEndpoint": "",
+ "UserApiEndpoint": ""
}
} \ No newline at end of file
diff --git a/doc/README.md b/doc/README.md
index 6bf96492a..7713c40ab 100644
--- a/doc/README.md
+++ b/doc/README.md
@@ -23,3 +23,7 @@
- [Code Contribution Guidelines](developer/code-contribution.md)
- [Developer Machine Setup](install/dev-setup.md)
- [Mattermost Style Guide](developer/style-guide.md)
+
+## End User Help
+
+- [Mattermost Markdown Formatting](help/enduser/markdown.md)
diff --git a/doc/developer/code-contribution.md b/doc/developer/code-contribution.md
index 708b324a0..51521be1b 100644
--- a/doc/developer/code-contribution.md
+++ b/doc/developer/code-contribution.md
@@ -33,25 +33,6 @@ git checkout -b <branch name>
1. Please add yourself to the Mattermost [approved contributor list](https://docs.google.com/spreadsheets/d/1NTCeG-iL_VS9bFqtmHSfwETo5f-8MQ7oMDE5IUYJi_Y/pubhtml?gid=0&single=true) prior to submitting by completing the [contributor license agreement](http://www.mattermost.org/mattermost-contributor-agreement/).
- For pull requests made by contributors not yet added to the approved contributor list, a reviewer may respond:
-
- ```
-Thanks @[GITHUB_USERNAME] for the pull request!
-
-Before we can review, we need to add you to the list of approved contributors for the Mattermost project.
-
-**Please help complete the Mattermost [contribution license agreement](http://www.mattermost.org/mattermost-contributor-agreement/)?**
-
-This is a standard procedure for many open source projects. You can view a list of past contributors who have completed the form [here](https://docs.google.com/spreadsheets/d/1NTCeG-iL_VS9bFqtmHSfwETo5f-8MQ7oMDE5IUYJi_Y/pubhtml?gid=0&single=true).
-
-After completing the form, it should be processed within 24 hours and reviewers for your pull request will be able to proceed.
-
-Please let us know if you have any questions.
-
-We are very happy to have you join our growing community!
-```
-
-
2. When you submit your pull request please include the Ticket ID at the beginning of your pull request comment, followed by a colon.
For example, for a ticket ID `PLT-394` start your comment with: `PLT-394:`. See [previously closed pull requests](https://github.com/mattermost/platform/pulls?q=is%3Apr+is%3Aclosed) for examples.
diff --git a/doc/help/enduser/markdown.md b/doc/help/enduser/markdown.md
new file mode 100644
index 000000000..9e2342a0b
--- /dev/null
+++ b/doc/help/enduser/markdown.md
@@ -0,0 +1,152 @@
+# Markdown Help
+
+Markdown makes it easy to format messages. Type a message as you normally would, and use these rules to render it with special formatting.
+
+## Text Style:
+
+You can use either `_` or `*` around a word to make it italic. Use two to make it bold.
+
+* `_italics_` renders as _italics_
+* `**bold**` renders as **bold**
+* `**_bold-italic_**` renders as **_bold-italics_**
+* `~~strikethrough~~` renders as ~~strikethrough~~
+
+## Code:
+
+Create a code block by indenting four spaces, or by placing ``` on the line above and below your code.
+
+Example:
+
+ ```
+ code block
+ ```
+
+Renders as:
+```
+code block
+```
+
+Create in-line monospaced font by surrounding it with back spaces.
+```
+`monospace`
+```
+Renders as: `monospace`.
+
+## Links:
+
+Create labeled links by putting the desired text in square brackets and the associated link in normal brackets.
+
+`[Check out Mattermost!](www.mattermost.com)`
+
+Renders as: [Check out Mattermost!](www.mattermost.com)
+
+## In-line Images
+
+Create in-line images using an `!` followed by the alt text in square brackets and the link in normal brackets. Add hover text by placing it in quotes after the link.
+```
+![alt text](link "hover text")
+
+and
+
+[![Build Status](https://travis-ci.org/mattermost/platform.svg?branch=master)](https://travis-ci.org/mattermost/platform) [![Github](https://assets-cdn.github.com/favicon.ico)](https://github.com/mattermost/platform)
+```
+Renders as:
+
+![alt text](link "hover text")
+
+and
+
+[![Build Status](https://travis-ci.org/mattermost/platform.svg?branch=master)](https://travis-ci.org/mattermost/platform) [![Github](https://assets-cdn.github.com/favicon.ico)](https://github.com/mattermost/platform)
+
+## Emojis
+
+Check out a full list of emojis [here](http://www.emoji-cheat-sheet.com/).
+
+```
+:smile: :+1: :sheep:
+```
+Renders as:
+:smile: :+1: :sheep:
+
+## Lines:
+
+Create a line by using three `*`, `_`, or `-`.
+
+`***` renders as:
+***
+
+## Block quotes:
+
+Create block quotes using `>`.
+
+`> block quotes` renders as:
+> block quotes
+
+## Lists:
+
+Create a list by using `*` or `-` as bullets. Indent a bullet point by adding two spaces in front of it.
+```
+* list item one
+* list item two
+ * item two sub-point
+```
+Renders as:
+* list item one
+* list item two
+ * item two sub-point
+
+Make it an ordered list by using numbers instead:
+```
+1. Item one
+2. Item two
+```
+Renders as:
+1. Item one
+2. Item two
+
+## Tables:
+
+Create a table by placing a dashed line under the header row and separating the columns with a pipe `|`. (The columns don’t need to line up exactly for it to work). Choose how to align table columns by including colons `:` within the header row.
+```
+| Left-Aligned  | Center Aligned  | Right Aligned |
+| :------------ |:---------------:| -----:|
+| Left column 1 | this text       |  $100 |
+| Left column 2 | is              |   $10 |
+| Left column 3 | centered        |    $1 |
+```
+
+Renders as:
+
+| Left-Aligned  | Center Aligned  | Right Aligned |
+| :------------ |:---------------:| -----:|
+| Left column 1 | this text       |  $100 |
+| Left column 2 | is              |   $10 |
+| Left column 3 | centered        |    $1 |
+
+## Headings:
+
+Make a heading by typing # and a space before your title. For smaller headings, use more #’s.
+```
+# Large heading
+## Smaller heading
+### Even smaller heading
+```
+Renders as:
+# Large Heading
+## Smaller Heading
+### Even smaller heading
+
+Alternatively, for the large heading you can underline the text using `===`. For the smaller heading you can underline using `---`
+```
+Large Heading
+=============
+
+Smaller Heading
+--------------
+```
+Renders as:
+Large Heading
+=============
+
+Smaller Heading
+--------------
diff --git a/doc/install/single-container-install.md b/doc/install/single-container-install.md
index 772f3becf..fa5265773 100644
--- a/doc/install/single-container-install.md
+++ b/doc/install/single-container-install.md
@@ -4,11 +4,11 @@ The following install instructions are for single-container installs of Mattermo
### Mac OSX ###
-1. Install Boot2Docker using instructions at: http://docs.docker.com/installation/mac/
- 1. Start Boot2Docker from the command line and run: `boot2docker init eval “$(boot2docker shellinit)”`
-2. Get your Docker IP address with: `boot2docker ip`
+1. Install Docker Toolbox using instructions at: http://docs.docker.com/installation/mac/
+ 1. Start Docker Toolbox from the command line and run: `docker-machine create -d virtualbox dev”`
+2. Get your Docker IP address with: `docker-machine ip dev`
3. Use `sudo nano /etc/hosts` to add `<Docker IP> dockerhost` to your /etc/hosts file
-4. Run: `boot2docker shellinit` and copy the export statements to your ~/.bash\_profile by running `sudo nano ~/.bash_profile`. Then run: `source ~/.bash_profile`
+4. Run: `docker-machine env dev` and copy the export statements to your ~/.bash\_profile by running `sudo nano ~/.bash_profile`. Then run: `source ~/.bash_profile`
5. Run: `docker run --name mattermost-dev -d --publish 8065:80 mattermost/platform`
6. When docker is done fetching the image, open http://dockerhost:8065/ in your browser.
diff --git a/docker/dev/config_docker.json b/docker/dev/config_docker.json
index aceeb95b4..06fee9bd5 100644
--- a/docker/dev/config_docker.json
+++ b/docker/dev/config_docker.json
@@ -1,81 +1,73 @@
{
- "LogSettings": {
- "ConsoleEnable": true,
- "ConsoleLevel": "INFO",
- "FileEnable": true,
- "FileLevel": "INFO",
- "FileFormat": "",
- "FileLocation": ""
- },
"ServiceSettings": {
- "SiteName": "Mattermost",
- "Mode" : "dev",
- "AllowTesting" : true,
- "UseSSL": false,
- "Port": "80",
- "Version": "developer",
- "Shards": {
- },
- "InviteSalt": "gxHVDcKUyP2y1eiyW8S8na1UYQAfq6J6",
- "PublicLinkSalt": "TO3pTyXIZzwHiwyZgGql7lM7DG3zeId4",
- "ResetSalt": "IPxFzSfnDFsNsRafZxz8NaYqFKhf9y2t",
- "AnalyticsUrl": "",
- "UseLocalStorage": true,
- "StorageDirectory": "/mattermost/data/",
- "AllowedLoginAttempts": 10,
- "DisableEmailSignUp": false,
- "EnableOAuthServiceProvider": false
+ "ListenAddress": ":80",
+ "MaximumLoginAttempts": 10,
+ "SegmentDeveloperKey": "",
+ "GoogleDeveloperKey": "",
+ "EnableOAuthServiceProvider": false,
+ "EnableIncomingWebhooks": false,
+ "EnableTesting": false
},
- "SSOSettings": {
- "gitlab": {
- "Allow": false,
- "Secret" : "",
- "Id": "",
- "Scope": "",
- "AuthEndpoint": "",
- "TokenEndpoint": "",
- "UserApiEndpoint": ""
- }
+ "TeamSettings": {
+ "SiteName": "Mattermost",
+ "MaxUsersPerTeam": 50,
+ "EnableTeamCreation": true,
+ "EnableUserCreation": true,
+ "RestrictCreationToDomains": ""
},
"SqlSettings": {
"DriverName": "mysql",
- "DataSource": "mmuser:mostest@tcp(localhost:3306)/mattermost_test?charset=utf8mb4,utf8",
- "DataSourceReplicas": ["mmuser:mostest@tcp(localhost:3306)/mattermost_test?charset=utf8mb4,utf8"],
+ "DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8",
+ "DataSourceReplicas": [],
"MaxIdleConns": 10,
"MaxOpenConns": 10,
"Trace": false,
- "AtRestEncryptKey": "Ya0xMrybACJ3sZZVWQC7e31h5nSDWZFS"
+ "AtRestEncryptKey": "7rAh6iwQCkV4cA1Gsg3fgGOXJAQ43QV"
},
- "AWSSettings": {
- "S3AccessKeyId": "",
- "S3SecretAccessKey": "",
- "S3Bucket": "",
- "S3Region": ""
+ "LogSettings": {
+ "EnableConsole": false,
+ "ConsoleLevel": "INFO",
+ "EnableFile": true,
+ "FileLevel": "INFO",
+ "FileFormat": "",
+ "FileLocation": ""
},
- "ImageSettings": {
+ "FileSettings": {
+ "DriverName": "local",
+ "Directory": "/mattermost/data/",
+ "EnablePublicLink": true,
+ "PublicLinkSalt": "LhaAWC6lYEKHTkBKsvyXNIOfUIT37AX",
"ThumbnailWidth": 120,
"ThumbnailHeight": 100,
"PreviewWidth": 1024,
"PreviewHeight": 0,
"ProfileWidth": 128,
"ProfileHeight": 128,
- "InitialFont": "luximbi.ttf"
+ "InitialFont": "luximbi.ttf",
+ "AmazonS3AccessKeyId": "",
+ "AmazonS3SecretAccessKey": "",
+ "AmazonS3Bucket": "",
+ "AmazonS3Region": ""
},
"EmailSettings": {
- "ByPassEmail" : true,
+ "EnableSignUpWithEmail": true,
+ "SendEmailNotifications": false,
+ "RequireEmailVerification": false,
+ "FeedbackName": "",
+ "FeedbackEmail": "",
"SMTPUsername": "",
"SMTPPassword": "",
"SMTPServer": "",
- "UseTLS": false,
- "UseStartTLS": false,
- "FeedbackEmail": "",
- "FeedbackName": "",
+ "SMTPPort": "",
+ "ConnectionSecurity": "",
+ "InviteSalt": "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9Yo",
+ "PasswordResetSalt": "vZ4DcKyVVRlKHHJpexcuXzojkE5PZ5e",
"ApplePushServer": "",
"ApplePushCertPublic": "",
"ApplePushCertPrivate": ""
},
"RateLimitSettings": {
- "UseRateLimiter": true,
+ "EnableRateLimiter": true,
"PerSec": 10,
"MemoryStoreSize": 10000,
"VaryByRemoteAddr": true,
@@ -83,22 +75,15 @@
},
"PrivacySettings": {
"ShowEmailAddress": true,
- "ShowPhoneNumber": true,
- "ShowSkypeId": true,
"ShowFullName": true
},
- "TeamSettings": {
- "MaxUsersPerTeam": 150,
- "AllowPublicLink": true,
- "AllowValetDefault": false,
- "TermsLink": "/static/help/configure_links.html",
- "PrivacyLink": "/static/help/configure_links.html",
- "AboutLink": "/static/help/configure_links.html",
- "HelpLink": "/static/help/configure_links.html",
- "ReportProblemLink": "/static/help/configure_links.html",
- "TourLink": "/static/help/configure_links.html",
- "DefaultThemeColor": "#2389D7",
- "DisableTeamCreation": false,
- "RestrictCreationToDomains": ""
+ "GitLabSettings": {
+ "Enable": false,
+ "Secret": "",
+ "Id": "",
+ "Scope": "",
+ "AuthEndpoint": "",
+ "TokenEndpoint": "",
+ "UserApiEndpoint": ""
}
-}
+} \ No newline at end of file
diff --git a/docker/local/config_docker.json b/docker/local/config_docker.json
index bc42951b8..06fee9bd5 100644
--- a/docker/local/config_docker.json
+++ b/docker/local/config_docker.json
@@ -1,81 +1,73 @@
{
- "LogSettings": {
- "ConsoleEnable": true,
- "ConsoleLevel": "INFO",
- "FileEnable": true,
- "FileLevel": "INFO",
- "FileFormat": "",
- "FileLocation": ""
- },
"ServiceSettings": {
- "SiteName": "Mattermost",
- "Mode" : "dev",
- "AllowTesting" : true,
- "UseSSL": false,
- "Port": "80",
- "Version": "developer",
- "Shards": {
- },
- "InviteSalt": "gxHVDcKUyP2y1eiyW8S8na1UYQAfq6J6",
- "PublicLinkSalt": "TO3pTyXIZzwHiwyZgGql7lM7DG3zeId4",
- "ResetSalt": "IPxFzSfnDFsNsRafZxz8NaYqFKhf9y2t",
- "AnalyticsUrl": "",
- "UseLocalStorage": true,
- "StorageDirectory": "/mattermost/data/",
- "AllowedLoginAttempts": 10,
- "DisableEmailSignUp": false,
- "EnableOAuthServiceProvider": false
+ "ListenAddress": ":80",
+ "MaximumLoginAttempts": 10,
+ "SegmentDeveloperKey": "",
+ "GoogleDeveloperKey": "",
+ "EnableOAuthServiceProvider": false,
+ "EnableIncomingWebhooks": false,
+ "EnableTesting": false
},
- "SSOSettings": {
- "gitlab": {
- "Allow": false,
- "Secret" : "",
- "Id": "",
- "Scope": "",
- "AuthEndpoint": "",
- "TokenEndpoint": "",
- "UserApiEndpoint": ""
- }
+ "TeamSettings": {
+ "SiteName": "Mattermost",
+ "MaxUsersPerTeam": 50,
+ "EnableTeamCreation": true,
+ "EnableUserCreation": true,
+ "RestrictCreationToDomains": ""
},
"SqlSettings": {
"DriverName": "mysql",
- "DataSource": "mmuser:mostest@tcp(localhost:3306)/mattermost_test?charset=utf8mb4,utf8",
- "DataSourceReplicas": ["mmuser:mostest@tcp(localhost:3306)/mattermost_test?charset=utf8mb4,utf8"],
+ "DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8",
+ "DataSourceReplicas": [],
"MaxIdleConns": 10,
"MaxOpenConns": 10,
"Trace": false,
- "AtRestEncryptKey": "Ya0xMrybACJ3sZZVWQC7e31h5nSDWZFS"
+ "AtRestEncryptKey": "7rAh6iwQCkV4cA1Gsg3fgGOXJAQ43QV"
},
- "AWSSettings": {
- "S3AccessKeyId": "",
- "S3SecretAccessKey": "",
- "S3Bucket": "",
- "S3Region": ""
+ "LogSettings": {
+ "EnableConsole": false,
+ "ConsoleLevel": "INFO",
+ "EnableFile": true,
+ "FileLevel": "INFO",
+ "FileFormat": "",
+ "FileLocation": ""
},
- "ImageSettings": {
+ "FileSettings": {
+ "DriverName": "local",
+ "Directory": "/mattermost/data/",
+ "EnablePublicLink": true,
+ "PublicLinkSalt": "LhaAWC6lYEKHTkBKsvyXNIOfUIT37AX",
"ThumbnailWidth": 120,
"ThumbnailHeight": 100,
"PreviewWidth": 1024,
"PreviewHeight": 0,
"ProfileWidth": 128,
"ProfileHeight": 128,
- "InitialFont": "luximbi.ttf"
+ "InitialFont": "luximbi.ttf",
+ "AmazonS3AccessKeyId": "",
+ "AmazonS3SecretAccessKey": "",
+ "AmazonS3Bucket": "",
+ "AmazonS3Region": ""
},
"EmailSettings": {
- "ByPassEmail" : true,
+ "EnableSignUpWithEmail": true,
+ "SendEmailNotifications": false,
+ "RequireEmailVerification": false,
+ "FeedbackName": "",
+ "FeedbackEmail": "",
"SMTPUsername": "",
"SMTPPassword": "",
"SMTPServer": "",
- "UseTLS": false,
- "UseStartTLS": false,
- "FeedbackEmail": "",
- "FeedbackName": "",
+ "SMTPPort": "",
+ "ConnectionSecurity": "",
+ "InviteSalt": "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9Yo",
+ "PasswordResetSalt": "vZ4DcKyVVRlKHHJpexcuXzojkE5PZ5e",
"ApplePushServer": "",
"ApplePushCertPublic": "",
"ApplePushCertPrivate": ""
},
"RateLimitSettings": {
- "UseRateLimiter": true,
+ "EnableRateLimiter": true,
"PerSec": 10,
"MemoryStoreSize": 10000,
"VaryByRemoteAddr": true,
@@ -83,22 +75,15 @@
},
"PrivacySettings": {
"ShowEmailAddress": true,
- "ShowPhoneNumber": true,
- "ShowSkypeId": true,
"ShowFullName": true
},
- "TeamSettings": {
- "MaxUsersPerTeam": 150,
- "AllowPublicLink": true,
- "AllowValetDefault": false,
- "TermsLink": "/static/help/configure_links.html",
- "PrivacyLink": "/static/help/configure_links.html",
- "AboutLink": "/static/help/configure_links.html",
- "HelpLink": "/static/help/configure_links.html",
- "ReportProblemLink": "/static/help/configure_links.html",
- "TourLink": "/static/help/configure_links.html",
- "DefaultThemeColor": "#2389D7",
- "DisableTeamCreation": false,
- "RestrictCreationToDomains": ""
+ "GitLabSettings": {
+ "Enable": false,
+ "Secret": "",
+ "Id": "",
+ "Scope": "",
+ "AuthEndpoint": "",
+ "TokenEndpoint": "",
+ "UserApiEndpoint": ""
}
-}
+} \ No newline at end of file
diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go
index 86b173c6a..a517b0c0e 100644
--- a/manualtesting/manual_testing.go
+++ b/manualtesting/manual_testing.go
@@ -53,7 +53,7 @@ func manualTest(c *api.Context, w http.ResponseWriter, r *http.Request) {
}
// Create a client for tests to use
- client := model.NewClient("http://localhost:" + utils.Cfg.ServiceSettings.Port)
+ client := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
// Check for username parameter and create a user if present
username, ok1 := params["username"]
diff --git a/mattermost.go b/mattermost.go
index f54bcf15f..ff7b0f3f3 100644
--- a/mattermost.go
+++ b/mattermost.go
@@ -57,7 +57,7 @@ func main() {
api.StartServer()
// If we allow testing then listen for manual testing URL hits
- if utils.Cfg.ServiceSettings.AllowTesting {
+ if utils.Cfg.ServiceSettings.EnableTesting {
manualtesting.InitManualTesting()
}
@@ -325,10 +325,10 @@ Usage:
-role="admin" The role used in other commands
valid values are
- "" - The empty role is basic user
+ "" - The empty role is basic user
permissions
"admin" - Represents a team admin and
- is used to help adminsiter one team.
+ is used to help administer one team.
"system_admin" - Represents a system
admin who has access to all teams
and configuration settings. This
diff --git a/model/channel.go b/model/channel.go
index 7d8edeee7..a7f007960 100644
--- a/model/channel.go
+++ b/model/channel.go
@@ -120,3 +120,11 @@ func (o *Channel) ExtraUpdated() {
func (o *Channel) PreExport() {
}
+
+func GetDMNameFromIds(userId1, userId2 string) string {
+ if userId1 > userId2 {
+ return userId2 + "__" + userId1
+ } else {
+ return userId1 + "__" + userId2
+ }
+}
diff --git a/model/client.go b/model/client.go
index f9127719f..26e00864d 100644
--- a/model/client.go
+++ b/model/client.go
@@ -21,6 +21,7 @@ const (
HEADER_ETAG_SERVER = "ETag"
HEADER_ETAG_CLIENT = "If-None-Match"
HEADER_FORWARDED = "X-Forwarded-For"
+ HEADER_REAL_IP = "X-Real-IP"
HEADER_FORWARDED_PROTO = "X-Forwarded-Proto"
HEADER_TOKEN = "token"
HEADER_BEARER = "BEARER"
@@ -48,7 +49,7 @@ func NewClient(url string) *Client {
return &Client{url, url + API_URL_SUFFIX, &http.Client{}, "", ""}
}
-func (c *Client) DoPost(url string, data, contentType string) (*http.Response, *AppError) {
+func (c *Client) DoPost(url, data, contentType string) (*http.Response, *AppError) {
rq, _ := http.NewRequest("POST", c.Url+url, strings.NewReader(data))
rq.Header.Set("Content-Type", contentType)
@@ -149,6 +150,16 @@ func (c *Client) CreateTeam(team *Team) (*Result, *AppError) {
}
}
+func (c *Client) GetAllTeams() (*Result, *AppError) {
+ if r, err := c.DoApiGet("/teams/all", "", ""); err != nil {
+ return nil, err
+ } else {
+
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil
+ }
+}
+
func (c *Client) FindTeamByName(name string, allServers bool) (*Result, *AppError) {
m := make(map[string]string)
m["name"] = name
@@ -207,15 +218,6 @@ func (c *Client) UpdateTeamDisplayName(data map[string]string) (*Result, *AppErr
}
}
-func (c *Client) UpdateValetFeature(data map[string]string) (*Result, *AppError) {
- if r, err := c.DoApiPost("/teams/update_valet_feature", MapToJson(data)); err != nil {
- return nil, err
- } else {
- return &Result{r.Header.Get(HEADER_REQUEST_ID),
- r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
- }
-}
-
func (c *Client) CreateUser(user *User, hash string) (*Result, *AppError) {
if r, err := c.DoApiPost("/users/create", user.ToJson()); err != nil {
return nil, err
@@ -253,7 +255,7 @@ func (c *Client) GetMe(etag string) (*Result, *AppError) {
}
func (c *Client) GetProfiles(teamId string, etag string) (*Result, *AppError) {
- if r, err := c.DoApiGet("/users/profiles", "", etag); err != nil {
+ if r, err := c.DoApiGet("/users/profiles/"+teamId, "", etag); err != nil {
return nil, err
} else {
return &Result{r.Header.Get(HEADER_REQUEST_ID),
@@ -403,6 +405,15 @@ func (c *Client) SaveConfig(config *Config) (*Result, *AppError) {
}
}
+func (c *Client) TestEmail(config *Config) (*Result, *AppError) {
+ if r, err := c.DoApiPost("/admin/test_email", config.ToJson()); err != nil {
+ return nil, err
+ } else {
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
+ }
+}
+
func (c *Client) CreateChannel(channel *Channel) (*Result, *AppError) {
if r, err := c.DoApiPost("/channels/create", channel.ToJson()); err != nil {
return nil, err
@@ -560,15 +571,6 @@ func (c *Client) CreatePost(post *Post) (*Result, *AppError) {
}
}
-func (c *Client) CreateValetPost(post *Post) (*Result, *AppError) {
- if r, err := c.DoApiPost("/channels/"+post.ChannelId+"/valet_create", post.ToJson()); err != nil {
- return nil, err
- } else {
- return &Result{r.Header.Get(HEADER_REQUEST_ID),
- r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil
- }
-}
-
func (c *Client) UpdatePost(post *Post) (*Result, *AppError) {
if r, err := c.DoApiPost("/channels/"+post.ChannelId+"/update", post.ToJson()); err != nil {
return nil, err
@@ -806,6 +808,42 @@ func (c *Client) GetAccessToken(data url.Values) (*Result, *AppError) {
}
}
+func (c *Client) CreateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) {
+ if r, err := c.DoApiPost("/hooks/incoming/create", hook.ToJson()); err != nil {
+ return nil, err
+ } else {
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil
+ }
+}
+
+func (c *Client) PostToWebhook(id, payload string) (*Result, *AppError) {
+ if r, err := c.DoPost("/hooks/"+id, payload, "application/x-www-form-urlencoded"); err != nil {
+ return nil, err
+ } else {
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), nil}, nil
+ }
+}
+
+func (c *Client) DeleteIncomingWebhook(data map[string]string) (*Result, *AppError) {
+ if r, err := c.DoApiPost("/hooks/incoming/delete", MapToJson(data)); err != nil {
+ return nil, err
+ } else {
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil
+ }
+}
+
+func (c *Client) ListIncomingWebhooks() (*Result, *AppError) {
+ if r, err := c.DoApiGet("/hooks/incoming/list", "", ""); err != nil {
+ return nil, err
+ } else {
+ return &Result{r.Header.Get(HEADER_REQUEST_ID),
+ r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookListFromJson(r.Body)}, nil
+ }
+}
+
func (c *Client) MockSession(sessionToken string) {
c.AuthToken = sessionToken
c.AuthType = HEADER_BEARER
diff --git a/model/config.go b/model/config.go
index 3b333dbe1..853e2bbc0 100644
--- a/model/config.go
+++ b/model/config.go
@@ -8,26 +8,29 @@ import (
"io"
)
+const (
+ CONN_SECURITY_NONE = ""
+ CONN_SECURITY_TLS = "TLS"
+ CONN_SECURITY_STARTTLS = "STARTTLS"
+
+ IMAGE_DRIVER_LOCAL = "local"
+ IMAGE_DRIVER_S3 = "amazons3"
+
+ SERVICE_GITLAB = "gitlab"
+)
+
type ServiceSettings struct {
- SiteName string
- Mode string
- AllowTesting bool
- UseSSL bool
- Port string
- Version string
- InviteSalt string
- PublicLinkSalt string
- ResetSalt string
- AnalyticsUrl string
- UseLocalStorage bool
- StorageDirectory string
- AllowedLoginAttempts int
- DisableEmailSignUp bool
+ ListenAddress string
+ MaximumLoginAttempts int
+ SegmentDeveloperKey string
+ GoogleDeveloperKey string
EnableOAuthServiceProvider bool
+ EnableIncomingWebhooks bool
+ EnableTesting bool
}
-type SSOSetting struct {
- Allow bool
+type SSOSettings struct {
+ Enable bool
Secret string
Id string
Scope string
@@ -47,87 +50,83 @@ type SqlSettings struct {
}
type LogSettings struct {
- ConsoleEnable bool
+ EnableConsole bool
ConsoleLevel string
- FileEnable bool
+ EnableFile bool
FileLevel string
FileFormat string
FileLocation string
}
-type AWSSettings struct {
- S3AccessKeyId string
- S3SecretAccessKey string
- S3Bucket string
- S3Region string
-}
-
-type ImageSettings struct {
- ThumbnailWidth uint
- ThumbnailHeight uint
- PreviewWidth uint
- PreviewHeight uint
- ProfileWidth uint
- ProfileHeight uint
- InitialFont string
+type FileSettings struct {
+ DriverName string
+ Directory string
+ EnablePublicLink bool
+ PublicLinkSalt string
+ ThumbnailWidth int
+ ThumbnailHeight int
+ PreviewWidth int
+ PreviewHeight int
+ ProfileWidth int
+ ProfileHeight int
+ InitialFont string
+ AmazonS3AccessKeyId string
+ AmazonS3SecretAccessKey string
+ AmazonS3Bucket string
+ AmazonS3Region string
}
type EmailSettings struct {
- ByPassEmail bool
- SMTPUsername string
- SMTPPassword string
- SMTPServer string
- UseTLS bool
- UseStartTLS bool
- FeedbackEmail string
- FeedbackName string
+ EnableSignUpWithEmail bool
+ SendEmailNotifications bool
+ RequireEmailVerification bool
+ FeedbackName string
+ FeedbackEmail string
+ SMTPUsername string
+ SMTPPassword string
+ SMTPServer string
+ SMTPPort string
+ ConnectionSecurity string
+ InviteSalt string
+ PasswordResetSalt string
+
+ // For Future Use
ApplePushServer string
ApplePushCertPublic string
ApplePushCertPrivate string
}
type RateLimitSettings struct {
- UseRateLimiter bool
- PerSec int
- MemoryStoreSize int
- VaryByRemoteAddr bool
- VaryByHeader string
+ EnableRateLimiter bool
+ PerSec int
+ MemoryStoreSize int
+ VaryByRemoteAddr bool
+ VaryByHeader string
}
type PrivacySettings struct {
ShowEmailAddress bool
- ShowPhoneNumber bool
- ShowSkypeId bool
ShowFullName bool
}
-type ClientSettings struct {
- SegmentDeveloperKey string
- GoogleDeveloperKey string
-}
-
type TeamSettings struct {
+ SiteName string
MaxUsersPerTeam int
- AllowPublicLink bool
- AllowValetDefault bool
- TourLink string
- DefaultThemeColor string
- DisableTeamCreation bool
+ EnableTeamCreation bool
+ EnableUserCreation bool
RestrictCreationToDomains string
}
type Config struct {
- LogSettings LogSettings
ServiceSettings ServiceSettings
+ TeamSettings TeamSettings
SqlSettings SqlSettings
- AWSSettings AWSSettings
- ImageSettings ImageSettings
+ LogSettings LogSettings
+ FileSettings FileSettings
EmailSettings EmailSettings
RateLimitSettings RateLimitSettings
PrivacySettings PrivacySettings
- ClientSettings ClientSettings
- TeamSettings TeamSettings
- SSOSettings map[string]SSOSetting
+ GitLabSettings SSOSettings
}
func (o *Config) ToJson() string {
@@ -139,6 +138,14 @@ func (o *Config) ToJson() string {
}
}
+func (o *Config) GetSSOService(service string) *SSOSettings {
+ if service == SERVICE_GITLAB {
+ return &o.GitLabSettings
+ }
+
+ return nil
+}
+
func ConfigFromJson(data io.Reader) *Config {
decoder := json.NewDecoder(data)
var o Config
diff --git a/model/team.go b/model/team.go
index 8b4f82830..f80fa3b11 100644
--- a/model/team.go
+++ b/model/team.go
@@ -27,7 +27,6 @@ type Team struct {
Type string `json:"type"`
CompanyName string `json:"company_name"`
AllowedDomains string `json:"allowed_domains"`
- AllowValet bool `json:"allow_valet"`
}
type Invites struct {
@@ -74,6 +73,26 @@ func TeamFromJson(data io.Reader) *Team {
}
}
+func TeamMapToJson(u map[string]*Team) string {
+ b, err := json.Marshal(u)
+ if err != nil {
+ return ""
+ } else {
+ return string(b)
+ }
+}
+
+func TeamMapFromJson(data io.Reader) map[string]*Team {
+ decoder := json.NewDecoder(data)
+ var teams map[string]*Team
+ err := decoder.Decode(&teams)
+ if err == nil {
+ return teams
+ } else {
+ return nil
+ }
+}
+
func (o *Team) Etag() string {
return Etag(o.Id, o.UpdateAt)
}
diff --git a/model/user.go b/model/user.go
index fdc519b99..5cb774478 100644
--- a/model/user.go
+++ b/model/user.go
@@ -23,7 +23,6 @@ const (
USER_NOTIFY_ALL = "all"
USER_NOTIFY_MENTION = "mention"
USER_NOTIFY_NONE = "none"
- BOT_USERNAME = "valet"
)
type User struct {
@@ -47,6 +46,7 @@ type User struct {
AllowMarketing bool `json:"allow_marketing"`
Props StringMap `json:"props"`
NotifyProps StringMap `json:"notify_props"`
+ ThemeProps StringMap `json:"theme_props"`
LastPasswordUpdate int64 `json:"last_password_update"`
LastPictureUpdate int64 `json:"last_picture_update"`
FailedAttempts int `json:"failed_attempts"`
@@ -108,6 +108,10 @@ func (u *User) IsValid() *AppError {
return NewAppError("User.IsValid", "Invalid user, password and auth data cannot both be set", "user_id="+u.Id)
}
+ if len(u.ThemeProps) > 2000 {
+ return NewAppError("User.IsValid", "Invalid theme", "user_id="+u.Id)
+ }
+
return nil
}
diff --git a/model/webhook.go b/model/webhook.go
new file mode 100644
index 000000000..9b4db3246
--- /dev/null
+++ b/model/webhook.go
@@ -0,0 +1,101 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package model
+
+import (
+ "encoding/json"
+ "io"
+)
+
+type IncomingWebhook struct {
+ Id string `json:"id"`
+ CreateAt int64 `json:"create_at"`
+ UpdateAt int64 `json:"update_at"`
+ DeleteAt int64 `json:"delete_at"`
+ UserId string `json:"user_id"`
+ ChannelId string `json:"channel_id"`
+ TeamId string `json:"team_id"`
+}
+
+func (o *IncomingWebhook) ToJson() string {
+ b, err := json.Marshal(o)
+ if err != nil {
+ return ""
+ } else {
+ return string(b)
+ }
+}
+
+func IncomingWebhookFromJson(data io.Reader) *IncomingWebhook {
+ decoder := json.NewDecoder(data)
+ var o IncomingWebhook
+ err := decoder.Decode(&o)
+ if err == nil {
+ return &o
+ } else {
+ return nil
+ }
+}
+
+func IncomingWebhookListToJson(l []*IncomingWebhook) string {
+ b, err := json.Marshal(l)
+ if err != nil {
+ return ""
+ } else {
+ return string(b)
+ }
+}
+
+func IncomingWebhookListFromJson(data io.Reader) []*IncomingWebhook {
+ decoder := json.NewDecoder(data)
+ var o []*IncomingWebhook
+ err := decoder.Decode(&o)
+ if err == nil {
+ return o
+ } else {
+ return nil
+ }
+}
+
+func (o *IncomingWebhook) IsValid() *AppError {
+
+ if len(o.Id) != 26 {
+ return NewAppError("IncomingWebhook.IsValid", "Invalid Id", "")
+ }
+
+ if o.CreateAt == 0 {
+ return NewAppError("IncomingWebhook.IsValid", "Create at must be a valid time", "id="+o.Id)
+ }
+
+ if o.UpdateAt == 0 {
+ return NewAppError("IncomingWebhook.IsValid", "Update at must be a valid time", "id="+o.Id)
+ }
+
+ if len(o.UserId) != 26 {
+ return NewAppError("IncomingWebhook.IsValid", "Invalid user id", "")
+ }
+
+ if len(o.ChannelId) != 26 {
+ return NewAppError("IncomingWebhook.IsValid", "Invalid channel id", "")
+ }
+
+ if len(o.TeamId) != 26 {
+ return NewAppError("IncomingWebhook.IsValid", "Invalid channel id", "")
+ }
+
+ return nil
+}
+
+func (o *IncomingWebhook) PreSave() {
+ if o.Id == "" {
+ o.Id = NewId()
+ }
+
+ o.CreateAt = GetMillis()
+ o.UpdateAt = o.CreateAt
+}
+
+func (o *IncomingWebhook) PreUpdate() {
+ o.UpdateAt = GetMillis()
+}
diff --git a/model/webhook_test.go b/model/webhook_test.go
new file mode 100644
index 000000000..ddbe18cd3
--- /dev/null
+++ b/model/webhook_test.go
@@ -0,0 +1,82 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package model
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestIncomingWebhookJson(t *testing.T) {
+ o := IncomingWebhook{Id: NewId()}
+ json := o.ToJson()
+ ro := IncomingWebhookFromJson(strings.NewReader(json))
+
+ if o.Id != ro.Id {
+ t.Fatal("Ids do not match")
+ }
+}
+
+func TestIncomingWebhookIsValid(t *testing.T) {
+ o := IncomingWebhook{}
+
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.Id = NewId()
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.CreateAt = GetMillis()
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.UpdateAt = GetMillis()
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.UserId = "123"
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.UserId = NewId()
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.ChannelId = "123"
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.ChannelId = NewId()
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.TeamId = "123"
+ if err := o.IsValid(); err == nil {
+ t.Fatal("should be invalid")
+ }
+
+ o.TeamId = NewId()
+ if err := o.IsValid(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestIncomingWebhookPreSave(t *testing.T) {
+ o := IncomingWebhook{}
+ o.PreSave()
+}
+
+func TestIncomingWebhookPreUpdate(t *testing.T) {
+ o := IncomingWebhook{}
+ o.PreUpdate()
+}
diff --git a/store/sql_session_store.go b/store/sql_session_store.go
index c1d2c852b..22411389d 100644
--- a/store/sql_session_store.go
+++ b/store/sql_session_store.go
@@ -140,6 +140,24 @@ func (me SqlSessionStore) Remove(sessionIdOrToken string) StoreChannel {
return storeChannel
}
+func (me SqlSessionStore) RemoveAllSessionsForTeam(teamId string) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId})
+ if err != nil {
+ result.Err = model.NewAppError("SqlSessionStore.RemoveAllSessionsForTeam", "We couldn't remove all the sessions for the team", "id="+teamId+", err="+err.Error())
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
func (me SqlSessionStore) CleanUpExpiredSessions(userId string) StoreChannel {
storeChannel := make(StoreChannel)
diff --git a/store/sql_session_store_test.go b/store/sql_session_store_test.go
index 4ae680556..3d8aafe25 100644
--- a/store/sql_session_store_test.go
+++ b/store/sql_session_store_test.go
@@ -80,6 +80,29 @@ func TestSessionRemove(t *testing.T) {
}
}
+func TestSessionRemoveAll(t *testing.T) {
+ Setup()
+
+ s1 := model.Session{}
+ s1.UserId = model.NewId()
+ s1.TeamId = model.NewId()
+ Must(store.Session().Save(&s1))
+
+ if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil {
+ t.Fatal(rs1.Err)
+ } else {
+ if rs1.Data.(*model.Session).Id != s1.Id {
+ t.Fatal("should match")
+ }
+ }
+
+ Must(store.Session().RemoveAllSessionsForTeam(s1.TeamId))
+
+ if rs2 := (<-store.Session().Get(s1.Id)); rs2.Err == nil {
+ t.Fatal("should have been removed")
+ }
+}
+
func TestSessionRemoveToken(t *testing.T) {
Setup()
diff --git a/store/sql_store.go b/store/sql_store.go
index adac47b4d..6dcf2e8cd 100644
--- a/store/sql_store.go
+++ b/store/sql_store.go
@@ -40,6 +40,7 @@ type SqlStore struct {
session SessionStore
oauth OAuthStore
system SystemStore
+ webhook WebhookStore
}
func NewSqlStore() Store {
@@ -50,11 +51,18 @@ func NewSqlStore() Store {
utils.Cfg.SqlSettings.DataSource, utils.Cfg.SqlSettings.MaxIdleConns,
utils.Cfg.SqlSettings.MaxOpenConns, utils.Cfg.SqlSettings.Trace)
- sqlStore.replicas = make([]*gorp.DbMap, len(utils.Cfg.SqlSettings.DataSourceReplicas))
- for i, replica := range utils.Cfg.SqlSettings.DataSourceReplicas {
- sqlStore.replicas[i] = setupConnection(fmt.Sprintf("replica-%v", i), utils.Cfg.SqlSettings.DriverName, replica,
+ if len(utils.Cfg.SqlSettings.DataSourceReplicas) == 0 {
+ sqlStore.replicas = make([]*gorp.DbMap, 1)
+ sqlStore.replicas[0] = setupConnection(fmt.Sprintf("replica-%v", 0), utils.Cfg.SqlSettings.DriverName, utils.Cfg.SqlSettings.DataSource,
utils.Cfg.SqlSettings.MaxIdleConns, utils.Cfg.SqlSettings.MaxOpenConns,
utils.Cfg.SqlSettings.Trace)
+ } else {
+ sqlStore.replicas = make([]*gorp.DbMap, len(utils.Cfg.SqlSettings.DataSourceReplicas))
+ for i, replica := range utils.Cfg.SqlSettings.DataSourceReplicas {
+ sqlStore.replicas[i] = setupConnection(fmt.Sprintf("replica-%v", i), utils.Cfg.SqlSettings.DriverName, replica,
+ utils.Cfg.SqlSettings.MaxIdleConns, utils.Cfg.SqlSettings.MaxOpenConns,
+ utils.Cfg.SqlSettings.Trace)
+ }
}
schemaVersion := sqlStore.GetCurrentSchemaVersion()
@@ -91,6 +99,7 @@ func NewSqlStore() Store {
sqlStore.session = NewSqlSessionStore(sqlStore)
sqlStore.oauth = NewSqlOAuthStore(sqlStore)
sqlStore.system = NewSqlSystemStore(sqlStore)
+ sqlStore.webhook = NewSqlWebhookStore(sqlStore)
sqlStore.master.CreateTablesIfNotExists()
@@ -102,6 +111,7 @@ func NewSqlStore() Store {
sqlStore.session.(*SqlSessionStore).UpgradeSchemaIfNeeded()
sqlStore.oauth.(*SqlOAuthStore).UpgradeSchemaIfNeeded()
sqlStore.system.(*SqlSystemStore).UpgradeSchemaIfNeeded()
+ sqlStore.webhook.(*SqlWebhookStore).UpgradeSchemaIfNeeded()
sqlStore.team.(*SqlTeamStore).CreateIndexesIfNotExists()
sqlStore.channel.(*SqlChannelStore).CreateIndexesIfNotExists()
@@ -111,6 +121,7 @@ func NewSqlStore() Store {
sqlStore.session.(*SqlSessionStore).CreateIndexesIfNotExists()
sqlStore.oauth.(*SqlOAuthStore).CreateIndexesIfNotExists()
sqlStore.system.(*SqlSystemStore).CreateIndexesIfNotExists()
+ sqlStore.webhook.(*SqlWebhookStore).CreateIndexesIfNotExists()
if model.IsPreviousVersion(schemaVersion) {
sqlStore.system.Update(&model.System{Name: "Version", Value: model.CurrentVersion})
@@ -304,26 +315,21 @@ func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string,
}
}
-// func (ss SqlStore) RemoveColumnIfExists(tableName string, columnName string) bool {
-
-// // XXX TODO FIXME this should be removed after 0.6.0
-// if utils.Cfg.SqlSettings.DriverName == "postgres" {
-// return false
-// }
+func (ss SqlStore) RemoveColumnIfExists(tableName string, columnName string) bool {
-// if !ss.DoesColumnExist(tableName, columnName) {
-// return false
-// }
+ if !ss.DoesColumnExist(tableName, columnName) {
+ return false
+ }
-// _, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " DROP COLUMN " + columnName)
-// if err != nil {
-// l4g.Critical("Failed to drop column %v", err)
-// time.Sleep(time.Second)
-// panic("Failed to drop column " + err.Error())
-// }
+ _, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " DROP COLUMN " + columnName)
+ if err != nil {
+ l4g.Critical("Failed to drop column %v", err)
+ time.Sleep(time.Second)
+ panic("Failed to drop column " + err.Error())
+ }
-// return true
-// }
+ return true
+}
// func (ss SqlStore) RenameColumnIfExists(tableName string, oldColumnName string, newColumnName string, colType string) bool {
@@ -469,6 +475,10 @@ func (ss SqlStore) System() SystemStore {
return ss.system
}
+func (ss SqlStore) Webhook() WebhookStore {
+ return ss.webhook
+}
+
type mattermConverter struct{}
func (me mattermConverter) ToDb(val interface{}) (interface{}, error) {
diff --git a/store/sql_team_store.go b/store/sql_team_store.go
index d2148c2e3..109fe5401 100644
--- a/store/sql_team_store.go
+++ b/store/sql_team_store.go
@@ -28,6 +28,7 @@ func NewSqlTeamStore(sqlStore *SqlStore) TeamStore {
}
func (s SqlTeamStore) UpgradeSchemaIfNeeded() {
+ s.RemoveColumnIfExists("Teams", "AllowValet")
}
func (s SqlTeamStore) CreateIndexesIfNotExists() {
@@ -195,7 +196,7 @@ func (s SqlTeamStore) GetTeamsForEmail(email string) StoreChannel {
return storeChannel
}
-func (s SqlTeamStore) GetForExport() StoreChannel {
+func (s SqlTeamStore) GetAll() StoreChannel {
storeChannel := make(StoreChannel)
go func() {
@@ -203,7 +204,7 @@ func (s SqlTeamStore) GetForExport() StoreChannel {
var data []*model.Team
if _, err := s.GetReplica().Select(&data, "SELECT * FROM Teams"); err != nil {
- result.Err = model.NewAppError("SqlTeamStore.GetForExport", "We could not get all teams", err.Error())
+ result.Err = model.NewAppError("SqlTeamStore.GetAllTeams", "We could not get all teams", err.Error())
}
result.Data = data
diff --git a/store/sql_user_store.go b/store/sql_user_store.go
index 778df367e..0a723d965 100644
--- a/store/sql_user_store.go
+++ b/store/sql_user_store.go
@@ -32,6 +32,7 @@ func NewSqlUserStore(sqlStore *SqlStore) UserStore {
table.ColMap("Roles").SetMaxSize(64)
table.ColMap("Props").SetMaxSize(4000)
table.ColMap("NotifyProps").SetMaxSize(2000)
+ table.ColMap("ThemeProps").SetMaxSize(2000)
table.SetUniqueTogether("Email", "TeamId")
table.SetUniqueTogether("Username", "TeamId")
}
@@ -40,6 +41,7 @@ func NewSqlUserStore(sqlStore *SqlStore) UserStore {
}
func (us SqlUserStore) UpgradeSchemaIfNeeded() {
+ us.CreateColumnIfNotExists("Users", "ThemeProps", "varchar(2000)", "character varying(2000)", "{}")
}
func (us SqlUserStore) CreateIndexesIfNotExists() {
@@ -479,3 +481,22 @@ func (us SqlUserStore) GetForExport(teamId string) StoreChannel {
return storeChannel
}
+
+func (us SqlUserStore) GetTotalUsersCount() StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users"); err != nil {
+ result.Err = model.NewAppError("SqlUserStore.GetTotalUsersCount", "We could not count the users", err.Error())
+ } else {
+ result.Data = count
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
diff --git a/store/sql_user_store_test.go b/store/sql_user_store_test.go
index ddd7e5bb8..e2a454023 100644
--- a/store/sql_user_store_test.go
+++ b/store/sql_user_store_test.go
@@ -42,7 +42,7 @@ func TestUserStoreSave(t *testing.T) {
t.Fatal("should be unique username")
}
- for i := 0; i < 150; i++ {
+ for i := 0; i < 50; i++ {
u1.Id = ""
u1.Email = model.NewId()
u1.Username = model.NewId()
@@ -206,6 +206,24 @@ func TestUserStoreGet(t *testing.T) {
}
}
+func TestUserCountt(t *testing.T) {
+ Setup()
+
+ u1 := model.User{}
+ u1.TeamId = model.NewId()
+ u1.Email = model.NewId()
+ Must(store.User().Save(&u1))
+
+ if result := <-store.User().GetTotalUsersCount(); result.Err != nil {
+ t.Fatal(result.Err)
+ } else {
+ count := result.Data.(int64)
+ if count <= 0 {
+ t.Fatal()
+ }
+ }
+}
+
func TestUserStoreGetProfiles(t *testing.T) {
Setup()
diff --git a/store/sql_webhook_store.go b/store/sql_webhook_store.go
new file mode 100644
index 000000000..e309f79e4
--- /dev/null
+++ b/store/sql_webhook_store.go
@@ -0,0 +1,128 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package store
+
+import (
+ "github.com/mattermost/platform/model"
+)
+
+type SqlWebhookStore struct {
+ *SqlStore
+}
+
+func NewSqlWebhookStore(sqlStore *SqlStore) WebhookStore {
+ s := &SqlWebhookStore{sqlStore}
+
+ for _, db := range sqlStore.GetAllConns() {
+ table := db.AddTableWithName(model.IncomingWebhook{}, "IncomingWebhooks").SetKeys(false, "Id")
+ table.ColMap("Id").SetMaxSize(26)
+ table.ColMap("UserId").SetMaxSize(26)
+ table.ColMap("ChannelId").SetMaxSize(26)
+ table.ColMap("TeamId").SetMaxSize(26)
+ }
+
+ return s
+}
+
+func (s SqlWebhookStore) UpgradeSchemaIfNeeded() {
+}
+
+func (s SqlWebhookStore) CreateIndexesIfNotExists() {
+ s.CreateIndexIfNotExists("idx_webhook_user_id", "IncomingWebhooks", "UserId")
+ s.CreateIndexIfNotExists("idx_webhook_team_id", "IncomingWebhooks", "TeamId")
+}
+
+func (s SqlWebhookStore) SaveIncoming(webhook *model.IncomingWebhook) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ if len(webhook.Id) > 0 {
+ result.Err = model.NewAppError("SqlWebhookStore.SaveIncoming",
+ "You cannot overwrite an existing IncomingWebhook", "id="+webhook.Id)
+ storeChannel <- result
+ close(storeChannel)
+ return
+ }
+
+ webhook.PreSave()
+ if result.Err = webhook.IsValid(); result.Err != nil {
+ storeChannel <- result
+ close(storeChannel)
+ return
+ }
+
+ if err := s.GetMaster().Insert(webhook); err != nil {
+ result.Err = model.NewAppError("SqlWebhookStore.SaveIncoming", "We couldn't save the IncomingWebhook", "id="+webhook.Id+", "+err.Error())
+ } else {
+ result.Data = webhook
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
+func (s SqlWebhookStore) GetIncoming(id string) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ var webhook model.IncomingWebhook
+
+ if err := s.GetReplica().SelectOne(&webhook, "SELECT * FROM IncomingWebhooks WHERE Id = :Id AND DeleteAt = 0", map[string]interface{}{"Id": id}); err != nil {
+ result.Err = model.NewAppError("SqlWebhookStore.GetIncoming", "We couldn't get the webhook", "id="+id+", err="+err.Error())
+ }
+
+ result.Data = &webhook
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
+func (s SqlWebhookStore) DeleteIncoming(webhookId string, time int64) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ _, err := s.GetMaster().Exec("Update IncomingWebhooks SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": webhookId})
+ if err != nil {
+ result.Err = model.NewAppError("SqlWebhookStore.DeleteIncoming", "We couldn't delete the webhook", "id="+webhookId+", err="+err.Error())
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
+func (s SqlWebhookStore) GetIncomingByUser(userId string) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ var webhooks []*model.IncomingWebhook
+
+ if _, err := s.GetReplica().Select(&webhooks, "SELECT * FROM IncomingWebhooks WHERE UserId = :UserId AND DeleteAt = 0", map[string]interface{}{"UserId": userId}); err != nil {
+ result.Err = model.NewAppError("SqlWebhookStore.GetIncomingByUser", "We couldn't get the webhook", "userId="+userId+", err="+err.Error())
+ }
+
+ result.Data = webhooks
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
diff --git a/store/sql_webhook_store_test.go b/store/sql_webhook_store_test.go
new file mode 100644
index 000000000..0a015eaf9
--- /dev/null
+++ b/store/sql_webhook_store_test.go
@@ -0,0 +1,77 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package store
+
+import (
+ "github.com/mattermost/platform/model"
+ "testing"
+)
+
+func TestIncomingWebhookStoreSaveIncoming(t *testing.T) {
+ Setup()
+
+ o1 := model.IncomingWebhook{}
+ o1.ChannelId = model.NewId()
+ o1.UserId = model.NewId()
+ o1.TeamId = model.NewId()
+
+ if err := (<-store.Webhook().SaveIncoming(&o1)).Err; err != nil {
+ t.Fatal("couldn't save item", err)
+ }
+
+ if err := (<-store.Webhook().SaveIncoming(&o1)).Err; err == nil {
+ t.Fatal("shouldn't be able to update from save")
+ }
+}
+
+func TestIncomingWebhookStoreGetIncoming(t *testing.T) {
+ Setup()
+
+ o1 := &model.IncomingWebhook{}
+ o1.ChannelId = model.NewId()
+ o1.UserId = model.NewId()
+ o1.TeamId = model.NewId()
+
+ o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
+
+ if r1 := <-store.Webhook().GetIncoming(o1.Id); r1.Err != nil {
+ t.Fatal(r1.Err)
+ } else {
+ if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
+ t.Fatal("invalid returned webhook")
+ }
+ }
+
+ if err := (<-store.Webhook().GetIncoming("123")).Err; err == nil {
+ t.Fatal("Missing id should have failed")
+ }
+}
+
+func TestIncomingWebhookStoreDelete(t *testing.T) {
+ Setup()
+
+ o1 := &model.IncomingWebhook{}
+ o1.ChannelId = model.NewId()
+ o1.UserId = model.NewId()
+ o1.TeamId = model.NewId()
+
+ o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
+
+ if r1 := <-store.Webhook().GetIncoming(o1.Id); r1.Err != nil {
+ t.Fatal(r1.Err)
+ } else {
+ if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
+ t.Fatal("invalid returned webhook")
+ }
+ }
+
+ if r2 := <-store.Webhook().DeleteIncoming(o1.Id, model.GetMillis()); r2.Err != nil {
+ t.Fatal(r2.Err)
+ }
+
+ if r3 := (<-store.Webhook().GetIncoming(o1.Id)); r3.Err == nil {
+ t.Log(r3.Data)
+ t.Fatal("Missing id should have failed")
+ }
+}
diff --git a/store/store.go b/store/store.go
index 1344c4ebe..23580f452 100644
--- a/store/store.go
+++ b/store/store.go
@@ -36,6 +36,7 @@ type Store interface {
Session() SessionStore
OAuth() OAuthStore
System() SystemStore
+ Webhook() WebhookStore
Close()
}
@@ -46,7 +47,7 @@ type TeamStore interface {
Get(id string) StoreChannel
GetByName(name string) StoreChannel
GetTeamsForEmail(domain string) StoreChannel
- GetForExport() StoreChannel
+ GetAll() StoreChannel
}
type ChannelStore interface {
@@ -102,6 +103,7 @@ type UserStore interface {
GetEtagForProfiles(teamId string) StoreChannel
UpdateFailedPasswordAttempts(userId string, attempts int) StoreChannel
GetForExport(teamId string) StoreChannel
+ GetTotalUsersCount() StoreChannel
}
type SessionStore interface {
@@ -109,6 +111,7 @@ type SessionStore interface {
Get(sessionIdOrToken string) StoreChannel
GetSessions(userId string) StoreChannel
Remove(sessionIdOrToken string) StoreChannel
+ RemoveAllSessionsForTeam(teamId string) StoreChannel
UpdateLastActivityAt(sessionId string, time int64) StoreChannel
UpdateRoles(userId string, roles string) StoreChannel
}
@@ -137,3 +140,10 @@ type SystemStore interface {
Update(system *model.System) StoreChannel
Get() StoreChannel
}
+
+type WebhookStore interface {
+ SaveIncoming(webhook *model.IncomingWebhook) StoreChannel
+ GetIncoming(id string) StoreChannel
+ GetIncomingByUser(userId string) StoreChannel
+ DeleteIncoming(webhookId string, time int64) StoreChannel
+}
diff --git a/utils/config.go b/utils/config.go
index dd2c17977..5d786699b 100644
--- a/utils/config.go
+++ b/utils/config.go
@@ -58,9 +58,9 @@ func FindDir(dir string) string {
func ConfigureCmdLineLog() {
ls := model.LogSettings{}
- ls.ConsoleEnable = true
+ ls.EnableConsole = true
ls.ConsoleLevel = "ERROR"
- ls.FileEnable = false
+ ls.EnableFile = false
configureLog(&ls)
}
@@ -68,7 +68,7 @@ func configureLog(s *model.LogSettings) {
l4g.Close()
- if s.ConsoleEnable {
+ if s.EnableConsole {
level := l4g.DEBUG
if s.ConsoleLevel == "INFO" {
level = l4g.INFO
@@ -79,7 +79,7 @@ func configureLog(s *model.LogSettings) {
l4g.AddFilter("stdout", level, l4g.NewConsoleLogWriter())
}
- if s.FileEnable {
+ if s.EnableFile {
var fileFormat = s.FileFormat
@@ -161,8 +161,6 @@ func getSanitizeOptions(c *model.Config) map[string]bool {
options := map[string]bool{}
options["fullname"] = c.PrivacySettings.ShowFullName
options["email"] = c.PrivacySettings.ShowEmailAddress
- options["skypeid"] = c.PrivacySettings.ShowSkypeId
- options["phonenumber"] = c.PrivacySettings.ShowPhoneNumber
return options
}
@@ -175,56 +173,24 @@ func getClientProperties(c *model.Config) map[string]string {
props["BuildDate"] = model.BuildDate
props["BuildHash"] = model.BuildHash
- props["SiteName"] = c.ServiceSettings.SiteName
- props["ByPassEmail"] = strconv.FormatBool(c.EmailSettings.ByPassEmail)
- props["FeedbackEmail"] = c.EmailSettings.FeedbackEmail
- props["ShowEmailAddress"] = strconv.FormatBool(c.PrivacySettings.ShowEmailAddress)
- props["AllowPublicLink"] = strconv.FormatBool(c.TeamSettings.AllowPublicLink)
- props["SegmentDeveloperKey"] = c.ClientSettings.SegmentDeveloperKey
- props["GoogleDeveloperKey"] = c.ClientSettings.GoogleDeveloperKey
- props["AnalyticsUrl"] = c.ServiceSettings.AnalyticsUrl
- props["ByPassEmail"] = strconv.FormatBool(c.EmailSettings.ByPassEmail)
- props["ProfileHeight"] = fmt.Sprintf("%v", c.ImageSettings.ProfileHeight)
- props["ProfileWidth"] = fmt.Sprintf("%v", c.ImageSettings.ProfileWidth)
- props["ProfileWidth"] = fmt.Sprintf("%v", c.ImageSettings.ProfileWidth)
+ props["SiteName"] = c.TeamSettings.SiteName
props["EnableOAuthServiceProvider"] = strconv.FormatBool(c.ServiceSettings.EnableOAuthServiceProvider)
- return props
-}
-
-func IsS3Configured() bool {
- if Cfg.AWSSettings.S3AccessKeyId == "" || Cfg.AWSSettings.S3SecretAccessKey == "" || Cfg.AWSSettings.S3Region == "" || Cfg.AWSSettings.S3Bucket == "" {
- return false
- }
-
- return true
-}
+ props["SegmentDeveloperKey"] = c.ServiceSettings.SegmentDeveloperKey
+ props["GoogleDeveloperKey"] = c.ServiceSettings.GoogleDeveloperKey
+ props["EnableIncomingWebhooks"] = strconv.FormatBool(c.ServiceSettings.EnableIncomingWebhooks)
-func GetAllowedAuthServices() []string {
- authServices := []string{}
- for name, service := range Cfg.SSOSettings {
- if service.Allow {
- authServices = append(authServices, name)
- }
- }
+ props["SendEmailNotifications"] = strconv.FormatBool(c.EmailSettings.SendEmailNotifications)
+ props["EnableSignUpWithEmail"] = strconv.FormatBool(c.EmailSettings.EnableSignUpWithEmail)
+ props["FeedbackEmail"] = c.EmailSettings.FeedbackEmail
- if !Cfg.ServiceSettings.DisableEmailSignUp {
- authServices = append(authServices, "email")
- }
+ props["EnableSignUpWithGitLab"] = strconv.FormatBool(c.GitLabSettings.Enable)
- return authServices
-}
-
-func IsServiceAllowed(s string) bool {
- if len(s) == 0 {
- return false
- }
+ props["ShowEmailAddress"] = strconv.FormatBool(c.PrivacySettings.ShowEmailAddress)
- if service, ok := Cfg.SSOSettings[s]; ok {
- if service.Allow {
- return true
- }
- }
+ props["EnablePublicLink"] = strconv.FormatBool(c.FileSettings.EnablePublicLink)
+ props["ProfileHeight"] = fmt.Sprintf("%v", c.FileSettings.ProfileHeight)
+ props["ProfileWidth"] = fmt.Sprintf("%v", c.FileSettings.ProfileWidth)
- return false
+ return props
}
diff --git a/utils/mail.go b/utils/mail.go
index 7cb178626..dd975155d 100644
--- a/utils/mail.go
+++ b/utils/mail.go
@@ -15,43 +15,22 @@ import (
"time"
)
-func CheckMailSettings() *model.AppError {
- if len(Cfg.EmailSettings.SMTPServer) == 0 || Cfg.EmailSettings.ByPassEmail {
- return model.NewAppError("CheckMailSettings", "No email settings present, mail will not be sent", "")
- }
- conn, err := connectToSMTPServer()
- if err != nil {
- return err
- }
- defer conn.Close()
- c, err2 := newSMTPClient(conn)
- if err2 != nil {
- return err
- }
- defer c.Quit()
- defer c.Close()
-
- return nil
-}
-
-func connectToSMTPServer() (net.Conn, *model.AppError) {
- host, _, _ := net.SplitHostPort(Cfg.EmailSettings.SMTPServer)
-
+func connectToSMTPServer(config *model.Config) (net.Conn, *model.AppError) {
var conn net.Conn
var err error
- if Cfg.EmailSettings.UseTLS {
+ if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_TLS {
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
- ServerName: host,
+ ServerName: config.EmailSettings.SMTPServer,
}
- conn, err = tls.Dial("tcp", Cfg.EmailSettings.SMTPServer, tlsconfig)
+ conn, err = tls.Dial("tcp", config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort, tlsconfig)
if err != nil {
return nil, model.NewAppError("SendMail", "Failed to open TLS connection", err.Error())
}
} else {
- conn, err = net.Dial("tcp", Cfg.EmailSettings.SMTPServer)
+ conn, err = net.Dial("tcp", config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort)
if err != nil {
return nil, model.NewAppError("SendMail", "Failed to open connection", err.Error())
}
@@ -60,24 +39,23 @@ func connectToSMTPServer() (net.Conn, *model.AppError) {
return conn, nil
}
-func newSMTPClient(conn net.Conn) (*smtp.Client, *model.AppError) {
- host, _, _ := net.SplitHostPort(Cfg.EmailSettings.SMTPServer)
- c, err := smtp.NewClient(conn, host)
+func newSMTPClient(conn net.Conn, config *model.Config) (*smtp.Client, *model.AppError) {
+ c, err := smtp.NewClient(conn, config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort)
if err != nil {
l4g.Error("Failed to open a connection to SMTP server %v", err)
return nil, model.NewAppError("SendMail", "Failed to open TLS connection", err.Error())
}
// GO does not support plain auth over a non encrypted connection.
// so if not tls then no auth
- auth := smtp.PlainAuth("", Cfg.EmailSettings.SMTPUsername, Cfg.EmailSettings.SMTPPassword, host)
- if Cfg.EmailSettings.UseTLS {
+ auth := smtp.PlainAuth("", config.EmailSettings.SMTPUsername, config.EmailSettings.SMTPPassword, config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort)
+ if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_TLS {
if err = c.Auth(auth); err != nil {
return nil, model.NewAppError("SendMail", "Failed to authenticate on SMTP server", err.Error())
}
- } else if Cfg.EmailSettings.UseStartTLS {
+ } else if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_STARTTLS {
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
- ServerName: host,
+ ServerName: config.EmailSettings.SMTPServer,
}
c.StartTLS(tlsconfig)
if err = c.Auth(auth); err != nil {
@@ -88,12 +66,16 @@ func newSMTPClient(conn net.Conn) (*smtp.Client, *model.AppError) {
}
func SendMail(to, subject, body string) *model.AppError {
+ return SendMailUsingConfig(to, subject, body, Cfg)
+}
+
+func SendMailUsingConfig(to, subject, body string, config *model.Config) *model.AppError {
- if len(Cfg.EmailSettings.SMTPServer) == 0 || Cfg.EmailSettings.ByPassEmail {
+ if !config.EmailSettings.SendEmailNotifications {
return nil
}
- fromMail := mail.Address{Cfg.EmailSettings.FeedbackName, Cfg.EmailSettings.FeedbackEmail}
+ fromMail := mail.Address{config.EmailSettings.FeedbackName, config.EmailSettings.FeedbackEmail}
toMail := mail.Address{"", to}
headers := make(map[string]string)
@@ -110,13 +92,13 @@ func SendMail(to, subject, body string) *model.AppError {
}
message += "\r\n<html><body>" + body + "</body></html>"
- conn, err1 := connectToSMTPServer()
+ conn, err1 := connectToSMTPServer(config)
if err1 != nil {
return err1
}
defer conn.Close()
- c, err2 := newSMTPClient(conn)
+ c, err2 := newSMTPClient(conn, config)
if err2 != nil {
return err2
}
diff --git a/web/react/components/activity_log_modal.jsx b/web/react/components/activity_log_modal.jsx
index 7cbd4021e..fe40385a0 100644
--- a/web/react/components/activity_log_modal.jsx
+++ b/web/react/components/activity_log_modal.jsx
@@ -25,7 +25,8 @@ export default class ActivityLogModal extends React.Component {
clientError: null
};
}
- submitRevoke(altId) {
+ submitRevoke(altId, e) {
+ e.preventDefault();
Client.revokeSession(altId,
function handleRevokeSuccess() {
AsyncClient.getSessions();
@@ -86,7 +87,7 @@ export default class ActivityLogModal extends React.Component {
<div>{`First time active: ${firstAccessTime.toDateString()}, ${lastAccessTime.toLocaleTimeString()}`}</div>
<div>{`OS: ${currentSession.props.os}`}</div>
<div>{`Browser: ${currentSession.props.browser}`}</div>
- <div>{`Session ID: ${currentSession.alt_id}`}</div>
+ <div>{`Session ID: ${currentSession.id}`}</div>
</div>
);
} else {
@@ -115,7 +116,7 @@ export default class ActivityLogModal extends React.Component {
</div>
<div className='activity-log__action'>
<button
- onClick={this.submitRevoke.bind(this, currentSession.alt_id)}
+ onClick={this.submitRevoke.bind(this, currentSession.id)}
className='btn btn-primary'
>
Logout
diff --git a/web/react/components/admin_console/admin_controller.jsx b/web/react/components/admin_console/admin_controller.jsx
index e82fe1b76..92f0bbdce 100644
--- a/web/react/components/admin_console/admin_controller.jsx
+++ b/web/react/components/admin_console/admin_controller.jsx
@@ -3,44 +3,118 @@
var AdminSidebar = require('./admin_sidebar.jsx');
var AdminStore = require('../../stores/admin_store.jsx');
+var TeamStore = require('../../stores/team_store.jsx');
var AsyncClient = require('../../utils/async_client.jsx');
var LoadingScreen = require('../loading_screen.jsx');
var EmailSettingsTab = require('./email_settings.jsx');
var LogSettingsTab = require('./log_settings.jsx');
var LogsTab = require('./logs.jsx');
+var FileSettingsTab = require('./image_settings.jsx');
+var PrivacySettingsTab = require('./privacy_settings.jsx');
+var RateSettingsTab = require('./rate_settings.jsx');
+var GitLabSettingsTab = require('./gitlab_settings.jsx');
+var SqlSettingsTab = require('./sql_settings.jsx');
+var TeamSettingsTab = require('./team_settings.jsx');
+var ServiceSettingsTab = require('./service_settings.jsx');
+var TeamUsersTab = require('./team_users.jsx');
export default class AdminController extends React.Component {
constructor(props) {
super(props);
this.selectTab = this.selectTab.bind(this);
+ this.removeSelectedTeam = this.removeSelectedTeam.bind(this);
+ this.addSelectedTeam = this.addSelectedTeam.bind(this);
this.onConfigListenerChange = this.onConfigListenerChange.bind(this);
+ this.onAllTeamsListenerChange = this.onAllTeamsListenerChange.bind(this);
+
+ var selectedTeams = AdminStore.getSelectedTeams();
+ if (selectedTeams == null) {
+ selectedTeams = {};
+ selectedTeams[TeamStore.getCurrentId()] = 'true';
+ AdminStore.saveSelectedTeams(selectedTeams);
+ }
this.state = {
- config: null,
- selected: 'email_settings'
+ config: AdminStore.getConfig(),
+ teams: AdminStore.getAllTeams(),
+ selectedTeams,
+ selected: 'service_settings',
+ selectedTeam: null
};
}
componentDidMount() {
AdminStore.addConfigChangeListener(this.onConfigListenerChange);
AsyncClient.getConfig();
+
+ AdminStore.addAllTeamsChangeListener(this.onAllTeamsListenerChange);
+ AsyncClient.getAllTeams();
}
componentWillUnmount() {
AdminStore.removeConfigChangeListener(this.onConfigListenerChange);
+ AdminStore.removeAllTeamsChangeListener(this.onAllTeamsListenerChange);
}
onConfigListenerChange() {
this.setState({
config: AdminStore.getConfig(),
- selected: this.state.selected
+ teams: AdminStore.getAllTeams(),
+ selectedTeams: AdminStore.getSelectedTeams(),
+ selected: this.state.selected,
+ selectedTeam: this.state.selectedTeam
});
}
- selectTab(tab) {
- this.setState({selected: tab});
+ onAllTeamsListenerChange() {
+ this.setState({
+ config: AdminStore.getConfig(),
+ teams: AdminStore.getAllTeams(),
+ selectedTeams: AdminStore.getSelectedTeams(),
+ selected: this.state.selected,
+ selectedTeam: this.state.selectedTeam
+
+ });
+ }
+
+ selectTab(tab, teamId) {
+ this.setState({
+ config: AdminStore.getConfig(),
+ teams: AdminStore.getAllTeams(),
+ selectedTeams: AdminStore.getSelectedTeams(),
+ selected: tab,
+ selectedTeam: teamId
+ });
+ }
+
+ removeSelectedTeam(teamId) {
+ var selectedTeams = AdminStore.getSelectedTeams();
+ Reflect.deleteProperty(selectedTeams, teamId);
+ AdminStore.saveSelectedTeams(selectedTeams);
+
+ this.setState({
+ config: AdminStore.getConfig(),
+ teams: AdminStore.getAllTeams(),
+ selectedTeams: AdminStore.getSelectedTeams(),
+ selected: this.state.selected,
+ selectedTeam: this.state.selectedTeam
+ });
+ }
+
+ addSelectedTeam(teamId) {
+ var selectedTeams = AdminStore.getSelectedTeams();
+ selectedTeams[teamId] = 'true';
+ AdminStore.saveSelectedTeams(selectedTeams);
+
+ this.setState({
+ config: AdminStore.getConfig(),
+ teams: AdminStore.getAllTeams(),
+ selectedTeams: AdminStore.getSelectedTeams(),
+ selected: this.state.selected,
+ selectedTeam: this.state.selectedTeam
+ });
}
render() {
@@ -53,6 +127,22 @@ export default class AdminController extends React.Component {
tab = <LogSettingsTab config={this.state.config} />;
} else if (this.state.selected === 'logs') {
tab = <LogsTab />;
+ } else if (this.state.selected === 'image_settings') {
+ tab = <FileSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'privacy_settings') {
+ tab = <PrivacySettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'rate_settings') {
+ tab = <RateSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'gitlab_settings') {
+ tab = <GitLabSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'sql_settings') {
+ tab = <SqlSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'team_settings') {
+ tab = <TeamSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'service_settings') {
+ tab = <ServiceSettingsTab config={this.state.config} />;
+ } else if (this.state.selected === 'team_users') {
+ tab = <TeamUsersTab team={this.state.teams[this.state.selectedTeam]} />;
}
}
@@ -64,7 +154,12 @@ export default class AdminController extends React.Component {
/>
<AdminSidebar
selected={this.state.selected}
+ selectedTeam={this.state.selectedTeam}
selectTab={this.selectTab}
+ teams={this.state.teams}
+ selectedTeams={this.state.selectedTeams}
+ removeSelectedTeam={this.removeSelectedTeam}
+ addSelectedTeam={this.addSelectedTeam}
/>
<div className='inner__wrap channel__wrap'>
<div className='row header'>
diff --git a/web/react/components/admin_console/admin_sidebar.jsx b/web/react/components/admin_console/admin_sidebar.jsx
index a6e689490..4b9ff3cb8 100644
--- a/web/react/components/admin_console/admin_sidebar.jsx
+++ b/web/react/components/admin_console/admin_sidebar.jsx
@@ -2,6 +2,7 @@
// See License.txt for license information.
var AdminSidebarHeader = require('./admin_sidebar_header.jsx');
+var SelectTeamModal = require('./select_team_modal.jsx');
export default class AdminSidebar extends React.Component {
constructor(props) {
@@ -9,28 +10,121 @@ export default class AdminSidebar extends React.Component {
this.isSelected = this.isSelected.bind(this);
this.handleClick = this.handleClick.bind(this);
+ this.removeTeam = this.removeTeam.bind(this);
+
+ this.showTeamSelect = this.showTeamSelect.bind(this);
+ this.teamSelectedModal = this.teamSelectedModal.bind(this);
+ this.teamSelectedModalDismissed = this.teamSelectedModalDismissed.bind(this);
this.state = {
+ showSelectModal: false
};
}
- handleClick(name, e) {
+ handleClick(name, teamId, e) {
e.preventDefault();
- this.props.selectTab(name);
+ this.props.selectTab(name, teamId);
}
- isSelected(name) {
+ isSelected(name, teamId) {
if (this.props.selected === name) {
- return 'active';
+ if (name === 'team_users') {
+ if (this.props.selectedTeam != null && this.props.selectedTeam === teamId) {
+ return 'active';
+ }
+ } else {
+ return 'active';
+ }
}
return '';
}
+ removeTeam(teamId, e) {
+ e.preventDefault();
+ Reflect.deleteProperty(this.props.selectedTeams, teamId);
+ this.props.removeSelectedTeam(teamId);
+
+ if (this.props.selected === 'team_users') {
+ if (this.props.selectedTeam != null && this.props.selectedTeam === teamId) {
+ this.props.selectTab('service_settings', null);
+ }
+ }
+ }
+
componentDidMount() {
}
+ showTeamSelect(e) {
+ e.preventDefault();
+ this.setState({showSelectModal: true});
+ }
+
+ teamSelectedModal(teamId) {
+ this.props.selectedTeams[teamId] = 'true';
+ this.setState({showSelectModal: false});
+ this.props.addSelectedTeam(teamId);
+ this.forceUpdate();
+ }
+
+ teamSelectedModalDismissed() {
+ this.setState({showSelectModal: false});
+ }
+
render() {
+ var count = '*';
+ var teams = 'Loading';
+
+ if (this.props.teams != null) {
+ count = '' + Object.keys(this.props.teams).length;
+
+ teams = [];
+ for (var key in this.props.selectedTeams) {
+ if (this.props.selectedTeams.hasOwnProperty(key)) {
+ var team = this.props.teams[key];
+
+ if (team != null) {
+ teams.push(
+ <ul
+ key={'team_' + team.id}
+ className='nav nav__sub-menu'
+ >
+ <li>
+ <a
+ href='#'
+ onClick={this.handleClick.bind(this, 'team_users', team.id)}
+ className={'nav__sub-menu-item ' + this.isSelected('team_users', team.id)}
+ >
+ {team.name}
+ <span
+ className='menu-icon--right menu__close'
+ onClick={this.removeTeam.bind(this, team.id)}
+ style={{cursor: 'pointer'}}
+ >
+ {'x'}
+ </span>
+ </a>
+ </li>
+ <li>
+ <ul className='nav nav__inner-menu'>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('team_users', team.id)}
+ onClick={this.handleClick.bind(this, 'team_users', team.id)}
+ >
+ {'- Users'}
+ </a>
+ </li>
+ </ul>
+ </li>
+ </ul>
+ );
+ }
+ }
+ }
+ }
+
return (
<div className='sidebar--left sidebar--collapsable'>
<div>
@@ -39,10 +133,45 @@ export default class AdminSidebar extends React.Component {
<li>
<ul className='nav nav__sub-menu'>
<li>
+ <h4>
+ <span className='icon fa fa-gear'></span>
+ <span>{'SETTINGS'}</span>
+ </h4>
+ </li>
+ </ul>
+ <ul className='nav nav__sub-menu padded'>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('service_settings')}
+ onClick={this.handleClick.bind(this, 'service_settings', null)}
+ >
+ {'Service Settings'}
+ </a>
+ </li>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('team_settings')}
+ onClick={this.handleClick.bind(this, 'team_settings', null)}
+ >
+ {'Team Settings'}
+ </a>
+ </li>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('sql_settings')}
+ onClick={this.handleClick.bind(this, 'sql_settings', null)}
+ >
+ {'SQL Settings'}
+ </a>
+ </li>
+ <li>
<a
href='#'
className={this.isSelected('email_settings')}
- onClick={this.handleClick.bind(this, 'email_settings')}
+ onClick={this.handleClick.bind(this, 'email_settings', null)}
>
{'Email Settings'}
</a>
@@ -50,8 +179,17 @@ export default class AdminSidebar extends React.Component {
<li>
<a
href='#'
+ className={this.isSelected('image_settings')}
+ onClick={this.handleClick.bind(this, 'image_settings', null)}
+ >
+ {'File Settings'}
+ </a>
+ </li>
+ <li>
+ <a
+ href='#'
className={this.isSelected('log_settings')}
- onClick={this.handleClick.bind(this, 'log_settings')}
+ onClick={this.handleClick.bind(this, 'log_settings', null)}
>
{'Log Settings'}
</a>
@@ -59,8 +197,66 @@ export default class AdminSidebar extends React.Component {
<li>
<a
href='#'
+ className={this.isSelected('rate_settings')}
+ onClick={this.handleClick.bind(this, 'rate_settings', null)}
+ >
+ {'Rate Limit Settings'}
+ </a>
+ </li>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('privacy_settings')}
+ onClick={this.handleClick.bind(this, 'privacy_settings', null)}
+ >
+ {'Privacy Settings'}
+ </a>
+ </li>
+ <li>
+ <a
+ href='#'
+ className={this.isSelected('gitlab_settings')}
+ onClick={this.handleClick.bind(this, 'gitlab_settings', null)}
+ >
+ {'GitLab Settings'}
+ </a>
+ </li>
+ </ul>
+ <ul className='nav nav__sub-menu'>
+ <li>
+ <h4>
+ <span className='icon fa fa-gear'></span>
+ <span>{'TEAMS (' + count + ')'}</span>
+ <span className='menu-icon--right'>
+ <a
+ href='#'
+ onClick={this.showTeamSelect}
+ >
+ <i className='fa fa-plus'></i>
+ </a>
+ </span>
+ </h4>
+ </li>
+ </ul>
+ <ul className='nav nav__sub-menu padded'>
+ <li>
+ {teams}
+ </li>
+ </ul>
+ <ul className='nav nav__sub-menu'>
+ <li>
+ <h4>
+ <span className='icon fa fa-gear'></span>
+ <span>{'OTHER'}</span>
+ </h4>
+ </li>
+ </ul>
+ <ul className='nav nav__sub-menu padded'>
+ <li>
+ <a
+ href='#'
className={this.isSelected('logs')}
- onClick={this.handleClick.bind(this, 'logs')}
+ onClick={this.handleClick.bind(this, 'logs', null)}
>
{'Logs'}
</a>
@@ -69,12 +265,24 @@ export default class AdminSidebar extends React.Component {
</li>
</ul>
</div>
+
+ <SelectTeamModal
+ teams={this.props.teams}
+ show={this.state.showSelectModal}
+ onModalSubmit={this.teamSelectedModal}
+ onModalDismissed={this.teamSelectedModalDismissed}
+ />
</div>
);
}
}
AdminSidebar.propTypes = {
+ teams: React.PropTypes.object,
+ selectedTeams: React.PropTypes.object,
+ removeSelectedTeam: React.PropTypes.func,
+ addSelectedTeam: React.PropTypes.func,
selected: React.PropTypes.string,
+ selectedTeam: React.PropTypes.string,
selectTab: React.PropTypes.func
}; \ No newline at end of file
diff --git a/web/react/components/admin_console/email_settings.jsx b/web/react/components/admin_console/email_settings.jsx
index e8fb25858..3b5ad2a1a 100644
--- a/web/react/components/admin_console/email_settings.jsx
+++ b/web/react/components/admin_console/email_settings.jsx
@@ -1,15 +1,179 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var crypto = require('crypto');
+
export default class EmailSettings extends React.Component {
constructor(props) {
super(props);
+ this.handleChange = this.handleChange.bind(this);
+ this.handleTestConnection = this.handleTestConnection.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.buildConfig = this.buildConfig.bind(this);
+ this.handleGenerateInvite = this.handleGenerateInvite.bind(this);
+ this.handleGenerateReset = this.handleGenerateReset.bind(this);
+
this.state = {
+ sendEmailNotifications: this.props.config.EmailSettings.SendEmailNotifications,
+ saveNeeded: false,
+ serverError: null,
+ emailSuccess: null,
+ emailFail: null
};
}
+ handleChange(action) {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ if (action === 'sendEmailNotifications_true') {
+ s.sendEmailNotifications = true;
+ }
+
+ if (action === 'sendEmailNotifications_false') {
+ s.sendEmailNotifications = false;
+ }
+
+ this.setState(s);
+ }
+
+ buildConfig() {
+ var config = this.props.config;
+ config.EmailSettings.EnableSignUpWithEmail = React.findDOMNode(this.refs.allowSignUpWithEmail).checked;
+ config.EmailSettings.SendEmailNotifications = React.findDOMNode(this.refs.sendEmailNotifications).checked;
+ config.EmailSettings.RequireEmailVerification = React.findDOMNode(this.refs.requireEmailVerification).checked;
+ config.EmailSettings.SendEmailNotifications = React.findDOMNode(this.refs.sendEmailNotifications).checked;
+ config.EmailSettings.FeedbackName = React.findDOMNode(this.refs.feedbackName).value.trim();
+ config.EmailSettings.FeedbackEmail = React.findDOMNode(this.refs.feedbackEmail).value.trim();
+ config.EmailSettings.SMTPServer = React.findDOMNode(this.refs.SMTPServer).value.trim();
+ config.EmailSettings.SMTPPort = React.findDOMNode(this.refs.SMTPPort).value.trim();
+ config.EmailSettings.SMTPUsername = React.findDOMNode(this.refs.SMTPUsername).value.trim();
+ config.EmailSettings.SMTPPassword = React.findDOMNode(this.refs.SMTPPassword).value.trim();
+ config.EmailSettings.ConnectionSecurity = React.findDOMNode(this.refs.ConnectionSecurity).value.trim();
+
+ config.EmailSettings.InviteSalt = React.findDOMNode(this.refs.InviteSalt).value.trim();
+ if (config.EmailSettings.InviteSalt === '') {
+ config.EmailSettings.InviteSalt = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ React.findDOMNode(this.refs.InviteSalt).value = config.EmailSettings.InviteSalt;
+ }
+
+ config.EmailSettings.PasswordResetSalt = React.findDOMNode(this.refs.PasswordResetSalt).value.trim();
+ if (config.EmailSettings.PasswordResetSalt === '') {
+ config.EmailSettings.PasswordResetSalt = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ React.findDOMNode(this.refs.PasswordResetSalt).value = config.EmailSettings.PasswordResetSalt;
+ }
+
+ return config;
+ }
+
+ handleGenerateInvite(e) {
+ e.preventDefault();
+ React.findDOMNode(this.refs.InviteSalt).value = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleGenerateReset(e) {
+ e.preventDefault();
+ React.findDOMNode(this.refs.PasswordResetSalt).value = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleTestConnection(e) {
+ e.preventDefault();
+ $('#connection-button').button('loading');
+
+ var config = this.buildConfig();
+
+ Client.testEmail(
+ config,
+ () => {
+ this.setState({
+ sendEmailNotifications: config.EmailSettings.SendEmailNotifications,
+ serverError: null,
+ saveNeeded: true,
+ emailSuccess: true,
+ emailFail: null
+ });
+ $('#connection-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ sendEmailNotifications: config.EmailSettings.SendEmailNotifications,
+ serverError: null,
+ saveNeeded: true,
+ emailSuccess: null,
+ emailFail: err.message + ' - ' + err.detailed_error
+ });
+ $('#connection-button').button('reset');
+ }
+ );
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.buildConfig();
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ sendEmailNotifications: config.EmailSettings.SendEmailNotifications,
+ serverError: null,
+ saveNeeded: false,
+ emailSuccess: null,
+ emailFail: null
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ sendEmailNotifications: config.EmailSettings.SendEmailNotifications,
+ serverError: err.message,
+ saveNeeded: true,
+ emailSuccess: null,
+ emailFail: null
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ var emailSuccess = '';
+ if (this.state.emailSuccess) {
+ emailSuccess = (
+ <div className='alert alert-success'>
+ <i className='fa fa-check'></i>{'No errors were reported while sending an email. Please check your inbox to make sure.'}
+ </div>
+ );
+ }
+
+ var emailFail = '';
+ if (this.state.emailFail) {
+ emailSuccess = (
+ <div className='alert alert-warning'>
+ <i className='fa fa-warning'></i>{'Connection unsuccessful: ' + this.state.emailFail}
+ </div>
+ );
+ }
+
return (
<div className='wrapper--fixed'>
<h3>{'Email Settings'}</h3>
@@ -17,295 +181,370 @@ export default class EmailSettings extends React.Component {
className='form-horizontal'
role='form'
>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='email'
+ htmlFor='allowSignUpWithEmail'
>
- {'Bypass Email: '}
- <a
- href='#'
- data-trigger='hover click'
- data-toggle='popover'
- data-position='bottom'
- data-content={'Here\'s some more help text inside a popover for the Bypass Email field just to show how popovers look.'}
- >
- {'(?)'}
- </a>
+ {'Allow Sign Up With Email: '}
</label>
<div className='col-sm-8'>
<label className='radio-inline'>
<input
type='radio'
- name='byPassEmail'
- value='option1'
+ name='allowSignUpWithEmail'
+ value='true'
+ ref='allowSignUpWithEmail'
+ defaultChecked={this.props.config.EmailSettings.EnableSignUpWithEmail}
+ onChange={this.handleChange.bind(this, 'allowSignUpWithEmail_true')}
/>
- {'True'}
+ {'true'}
</label>
<label className='radio-inline'>
<input
type='radio'
- name='byPassEmail'
- value='option2'
+ name='allowSignUpWithEmail'
+ value='false'
+ defaultChecked={!this.props.config.EmailSettings.EnableSignUpWithEmail}
+ onChange={this.handleChange.bind(this, 'allowSignUpWithEmail_false')}
/>
- {'False'}
+ {'false'}
</label>
- <p className='help-text'>{'This is some sample help text for the Bypass Email field'}</p>
+ <p className='help-text'>{'When true, Mattermost allows team creation and account signup using email and password. This value should be false only when you want to limit signup to a single-sign-on service like OAuth or LDAP.'}</p>
</div>
</div>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='smtpUsername'
+ htmlFor='sendEmailNotifications'
>
- {'SMTP Username:'}
+ {'Send Email Notifications: '}
</label>
<div className='col-sm-8'>
- <input
- type='email'
- className='form-control'
- id='smtpUsername'
- placeholder='Enter your SMTP username'
- value=''
- />
- <div className='help-text'>
- <div className='alert alert-warning'><i className='fa fa-warning'></i>{' This is some error text for the Bypass Email field'}</div>
- </div>
- <p className='help-text'>{'This is some sample help text for the SMTP username field'}</p>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='sendEmailNotifications'
+ value='true'
+ ref='sendEmailNotifications'
+ defaultChecked={this.props.config.EmailSettings.SendEmailNotifications}
+ onChange={this.handleChange.bind(this, 'sendEmailNotifications_true')}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='sendEmailNotifications'
+ value='false'
+ defaultChecked={!this.props.config.EmailSettings.SendEmailNotifications}
+ onChange={this.handleChange.bind(this, 'sendEmailNotifications_false')}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'Typically set to true in production. When true, Mattermost attempts to send email notifications. Developers may set this field to false to skip email setup for faster development.'}</p>
</div>
</div>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='smtpPassword'
+ htmlFor='requireEmailVerification'
>
- {'SMTP Password:'}
+ {'Require Email Verification: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='requireEmailVerification'
+ value='true'
+ ref='requireEmailVerification'
+ defaultChecked={this.props.config.EmailSettings.RequireEmailVerification}
+ onChange={this.handleChange.bind(this, 'requireEmailVerification_true')}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='requireEmailVerification'
+ value='false'
+ defaultChecked={!this.props.config.EmailSettings.RequireEmailVerification}
+ onChange={this.handleChange.bind(this, 'requireEmailVerification_false')}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'Typically set to true in production. When true, Mattermost requires email verification after account creation prior to allowing login. Developers may set this field to false so skip sending verification emails for faster development.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='feedbackName'
+ >
+ {'Feedback Name:'}
</label>
<div className='col-sm-8'>
<input
- type='password'
+ type='text'
className='form-control'
- id='smtpPassword'
- placeholder='Enter your SMTP password'
- value=''
+ id='feedbackName'
+ ref='feedbackName'
+ placeholder='Ex: "Mattermost Notification", "System", "No-Reply"'
+ defaultValue={this.props.config.EmailSettings.FeedbackName}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
/>
+ <p className='help-text'>{'Display name on email account used when sending notification emails from Mattermost.'}</p>
</div>
</div>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='smtpServer'
+ htmlFor='feedbackEmail'
>
- {'SMTP Server:'}
+ {'Feedback Email:'}
</label>
<div className='col-sm-8'>
<input
- type='text'
+ type='email'
className='form-control'
- id='smtpServer'
- placeholder='Enter your SMTP server'
- value=''
+ id='feedbackEmail'
+ ref='feedbackEmail'
+ placeholder='Ex: "mattermost@yourcompany.com", "admin@yourcompany.com"'
+ defaultValue={this.props.config.EmailSettings.FeedbackEmail}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
/>
- <div className='help-text'>
- <a
- href='#'
- className='help-link'
- >
- {'Test Connection'}
- </a>
- <div className='alert alert-success'><i className='fa fa-check'></i>{' Connection successful'}</div>
- <div className='alert alert-warning hide'><i className='fa fa-warning'></i>{' Connection unsuccessful'}</div>
- </div>
+ <p className='help-text'>{'Email address displayed on email account used when sending notification emails from Mattermost.'}</p>
</div>
</div>
+
<div className='form-group'>
- <label className='control-label col-sm-4'>{'Use TLS:'}</label>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='SMTPUsername'
+ >
+ {'SMTP Username:'}
+ </label>
<div className='col-sm-8'>
- <label className='radio-inline'>
- <input
- type='radio'
- name='tls'
- value='option1'
- />
- {'True'}
- </label>
- <label className='radio-inline'>
- <input
- type='radio'
- name='tls'
- value='option2'
- />
- {'False'}
- </label>
+ <input
+ type='text'
+ className='form-control'
+ id='SMTPUsername'
+ ref='SMTPUsername'
+ placeholder='Ex: "admin@yourcompany.com", "AKIADTOVBGERKLCBV"'
+ defaultValue={this.props.config.EmailSettings.SMTPUsername}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ <p className='help-text'>{' Obtain this credential from administrator setting up your email server.'}</p>
</div>
</div>
+
<div className='form-group'>
- <label className='control-label col-sm-4'>{'Use Start TLS:'}</label>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='SMTPPassword'
+ >
+ {'SMTP Password:'}
+ </label>
<div className='col-sm-8'>
- <label className='radio-inline'>
- <input
- type='radio'
- name='starttls'
- value='option1'
- />
- {'True'}
- </label>
- <label className='radio-inline'>
- <input
- type='radio'
- name='starttls'
- value='option2'
- />
- {'False'}
- </label>
+ <input
+ type='text'
+ className='form-control'
+ id='SMTPPassword'
+ ref='SMTPPassword'
+ placeholder='Ex: "yourpassword", "jcuS8PuvcpGhpgHhlcpT1Mx42pnqMxQY"'
+ defaultValue={this.props.config.EmailSettings.SMTPPassword}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ <p className='help-text'>{' Obtain this credential from administrator setting up your email server.'}</p>
</div>
</div>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='feedbackEmail'
+ htmlFor='SMTPServer'
>
- {'Feedback Email:'}
+ {'SMTP Server:'}
</label>
<div className='col-sm-8'>
<input
type='text'
className='form-control'
- id='feedbackEmail'
- placeholder='Enter your feedback email'
- value=''
+ id='SMTPServer'
+ ref='SMTPServer'
+ placeholder='Ex: "smtp.yourcompany.com", "email-smtp.us-east-1.amazonaws.com"'
+ defaultValue={this.props.config.EmailSettings.SMTPServer}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
/>
+ <p className='help-text'>{'Location of SMTP email server.'}</p>
</div>
</div>
+
<div className='form-group'>
<label
className='control-label col-sm-4'
- htmlFor='feedbackUsername'
+ htmlFor='SMTPPort'
>
- {'Feedback Username:'}
+ {'SMTP Port:'}
</label>
<div className='col-sm-8'>
<input
type='text'
className='form-control'
- id='feedbackUsername'
- placeholder='Enter your feedback username'
- value=''
+ id='SMTPPort'
+ ref='SMTPPort'
+ placeholder='Ex: "25", "465"'
+ defaultValue={this.props.config.EmailSettings.SMTPPort}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
/>
+ <p className='help-text'>{'Port of SMTP email server.'}</p>
</div>
</div>
+
<div className='form-group'>
- <div className='col-sm-offset-4 col-sm-8'>
- <div className='checkbox'>
- <label><input type='checkbox' />{'Remember me'}</label>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ConnectionSecurity'
+ >
+ {'Connection Security:'}
+ </label>
+ <div className='col-sm-8'>
+ <select
+ className='form-control'
+ id='ConnectionSecurity'
+ ref='ConnectionSecurity'
+ defaultValue={this.props.config.EmailSettings.ConnectionSecurity}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
+ >
+ <option value=''>{'None'}</option>
+ <option value='TLS'>{'TLS (Recommended)'}</option>
+ <option value='STARTTLS'>{'STARTTLS'}</option>
+ </select>
+ <div className='help-text'>
+ <table
+ className='table-bordered'
+ cellPadding='5'
+ >
+ <tr><td className='help-text'>{'None'}</td><td className='help-text'>{'Mattermost will send email over an unsecure connection.'}</td></tr>
+ <tr><td className='help-text'>{'TLS'}</td><td className='help-text'>{'Encrypts the communication between Mattermost and your email server.'}</td></tr>
+ <tr><td className='help-text'>{'STARTTLS'}</td><td className='help-text'>{'Takes an existing insecure connection and attempts to upgrade it to a secure connection using TLS.'}</td></tr>
+ </table>
+ </div>
+ <div className='help-text'>
+ <button
+ className='help-link'
+ onClick={this.handleTestConnection}
+ disabled={!this.state.sendEmailNotifications}
+ id='connection-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Testing...'}
+ >
+ {'Test Connection'}
+ </button>
+ {emailSuccess}
+ {emailFail}
</div>
</div>
</div>
- <div
- className='panel-group'
- id='accordion'
- role='tablist'
- aria-multiselectable='true'
- >
- <div className='panel panel-default'>
- <div
- className='panel-heading'
- role='tab'
- id='headingOne'
- >
- <h3 className='panel-title'>
- <a
- className='collapsed'
- role='button'
- data-toggle='collapse'
- data-parent='#accordion'
- href='#collapseOne'
- aria-expanded='true'
- aria-controls='collapseOne'
- >
- {'Advanced Settings '}
- <i className='fa fa-plus'></i>
- <i className='fa fa-minus'></i>
- </a>
- </h3>
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='InviteSalt'
+ >
+ {'Invite Salt:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='InviteSalt'
+ ref='InviteSalt'
+ placeholder='Ex "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9Yo"'
+ defaultValue={this.props.config.EmailSettings.InviteSalt}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ <p className='help-text'>{'32-character salt added to signing of email invites. Randomly generated on install. Click "Re-Generate" to create new salt.'}</p>
+ <div className='help-text'>
+ <button
+ className='help-link'
+ onClick={this.handleGenerateInvite}
+ disabled={!this.state.sendEmailNotifications}
+ >
+ {'Re-Generate'}
+ </button>
</div>
- <div
- id='collapseOne'
- className='panel-collapse collapse'
- role='tabpanel'
- aria-labelledby='headingOne'
- >
- <div className='panel-body'>
- <div className='form-group'>
- <label
- className='control-label col-sm-4'
- htmlFor='feedbackUsername'
- >
- {'Apple push server:'}
- </label>
- <div className='col-sm-8'>
- <input
- type='text'
- className='form-control'
- id='feedbackUsername'
- placeholder='Enter your Apple push server'
- value=''
- />
- <p className='help-text'>{'This is some sample help text for the Apple push server field'}</p>
- </div>
- </div>
- <div className='form-group'>
- <label
- className='control-label col-sm-4'
- htmlFor='feedbackUsername'
- >
- {'Apple push certificate public:'}
- </label>
- <div className='col-sm-8'>
- <input
- type='text'
- className='form-control'
- id='feedbackUsername'
- placeholder='Enter your public apple push certificate'
- value=''
- />
- </div>
- </div>
- <div className='form-group'>
- <label
- className='control-label col-sm-4'
- htmlFor='feedbackUsername'
- >
- {'Apple push certificate private:'}
- </label>
- <div className='col-sm-8'>
- <input
- type='text'
- className='form-control'
- id='feedbackUsername'
- placeholder='Enter your private apple push certificate'
- value=''
- />
- </div>
- </div>
- </div>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='PasswordResetSalt'
+ >
+ {'Password Reset Salt:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='PasswordResetSalt'
+ ref='PasswordResetSalt'
+ placeholder='Ex "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9Yo"'
+ defaultValue={this.props.config.EmailSettings.PasswordResetSalt}
+ onChange={this.handleChange}
+ disabled={!this.state.sendEmailNotifications}
+ />
+ <p className='help-text'>{'32-character salt added to signing of password reset emails. Randomly generated on install. Click "Re-Generate" to create new salt.'}</p>
+ <div className='help-text'>
+ <button
+ className='help-link'
+ onClick={this.handleGenerateReset}
+ disabled={!this.state.sendEmailNotifications}
+ >
+ {'Re-Generate'}
+ </button>
</div>
</div>
</div>
<div className='form-group'>
<div className='col-sm-12'>
+ {serverError}
<button
+ disabled={!this.state.saveNeeded}
type='submit'
- className='btn btn-primary'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
>
{'Save'}
</button>
</div>
</div>
+
</form>
</div>
);
}
-} \ No newline at end of file
+}
+
+EmailSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/gitlab_settings.jsx b/web/react/components/admin_console/gitlab_settings.jsx
new file mode 100644
index 000000000..1e10c5592
--- /dev/null
+++ b/web/react/components/admin_console/gitlab_settings.jsx
@@ -0,0 +1,277 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+
+export default class GitLabSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+
+ this.state = {
+ Allow: this.props.config.GitLabSettings.Allow,
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange(action) {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ if (action === 'AllowTrue') {
+ s.Allow = true;
+ }
+
+ if (action === 'AllowFalse') {
+ s.Allow = false;
+ }
+
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.GitLabSettings.Allow = React.findDOMNode(this.refs.Allow).checked;
+ config.GitLabSettings.Secret = React.findDOMNode(this.refs.Secret).value.trim();
+ config.GitLabSettings.Id = React.findDOMNode(this.refs.Id).value.trim();
+ config.GitLabSettings.Scope = React.findDOMNode(this.refs.Scope).value.trim();
+ config.GitLabSettings.AuthEndpoint = React.findDOMNode(this.refs.AuthEndpoint).value.trim();
+ config.GitLabSettings.TokenEndpoint = React.findDOMNode(this.refs.TokenEndpoint).value.trim();
+ config.GitLabSettings.UserApiEndpoint = React.findDOMNode(this.refs.UserApiEndpoint).value.trim();
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+
+ <h3>{'GitLab Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Allow'
+ >
+ {'Enable Sign Up With GitLab: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='Allow'
+ value='true'
+ ref='Allow'
+ defaultChecked={this.props.config.GitLabSettings.Allow}
+ onChange={this.handleChange.bind(this, 'AllowTrue')}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='Allow'
+ value='false'
+ defaultChecked={!this.props.config.GitLabSettings.Allow}
+ onChange={this.handleChange.bind(this, 'AllowFalse')}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When true, Mattermost allows team creation and account signup using GitLab OAuth. To configure, log in to your GitLab account and go to Applications -> Profile Settings. Enter Redirect URIs "<your-mattermost-url>/login/gitlab/complete" (example: http://localhost:8065/login/gitlab/complete) and "<your-mattermost-url>/signup/gitlab/complete". Then use "Secret" and "Id" fields to complete the options below.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Secret'
+ >
+ {'Secret:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='Secret'
+ ref='Secret'
+ placeholder='Ex "jcuS8PuvcpGhpgHhlcpT1Mx42pnqMxQY"'
+ defaultValue={this.props.config.GitLabSettings.Secret}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'Obtain this value via the instructions above for logging into GitLab.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Id'
+ >
+ {'Id:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='Id'
+ ref='Id'
+ placeholder='Ex "jcuS8PuvcpGhpgHhlcpT1Mx42pnqMxQY"'
+ defaultValue={this.props.config.GitLabSettings.Id}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'Obtain this value via the instructions above for logging into GitLab'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Scope'
+ >
+ {'Scope:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='Scope'
+ ref='Scope'
+ placeholder='Not currently used by GitLab. Please leave blank'
+ defaultValue={this.props.config.GitLabSettings.Scope}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'This field is not yet used by GitLab OAuth. Other OAuth providers may use this field to specify the scope of account data from OAuth provider that is sent to Mattermost.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AuthEndpoint'
+ >
+ {'Auth Endpoint:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AuthEndpoint'
+ ref='AuthEndpoint'
+ placeholder='Ex ""'
+ defaultValue={this.props.config.GitLabSettings.AuthEndpoint}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'Enter <your-gitlab-url>/oauth/authorize (example http://localhost:3000/oauth/authorize).'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='TokenEndpoint'
+ >
+ {'Token Endpoint:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='TokenEndpoint'
+ ref='TokenEndpoint'
+ placeholder='Ex ""'
+ defaultValue={this.props.config.GitLabSettings.TokenEndpoint}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'Enter <your-gitlab-url>/oauth/token.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='UserApiEndpoint'
+ >
+ {'User API Endpoint:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='UserApiEndpoint'
+ ref='UserApiEndpoint'
+ placeholder='Ex ""'
+ defaultValue={this.props.config.GitLabSettings.UserApiEndpoint}
+ onChange={this.handleChange}
+ disabled={!this.state.Allow}
+ />
+ <p className='help-text'>{'Enter <your-gitlab-url>/api/v3/user.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+GitLabSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/image_settings.jsx b/web/react/components/admin_console/image_settings.jsx
new file mode 100644
index 000000000..e52f516e8
--- /dev/null
+++ b/web/react/components/admin_console/image_settings.jsx
@@ -0,0 +1,496 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var crypto = require('crypto');
+
+export default class FileSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.handleGenerate = this.handleGenerate.bind(this);
+
+ this.state = {
+ saveNeeded: false,
+ serverError: null,
+ DriverName: this.props.config.FileSettings.DriverName
+ };
+ }
+
+ handleChange(action) {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ if (action === 'DriverName') {
+ s.DriverName = React.findDOMNode(this.refs.DriverName).value;
+ }
+
+ this.setState(s);
+ }
+
+ handleGenerate(e) {
+ e.preventDefault();
+ React.findDOMNode(this.refs.PublicLinkSalt).value = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.FileSettings.DriverName = React.findDOMNode(this.refs.DriverName).value;
+ config.FileSettings.Directory = React.findDOMNode(this.refs.Directory).value;
+ config.FileSettings.AmazonS3AccessKeyId = React.findDOMNode(this.refs.AmazonS3AccessKeyId).value;
+ config.FileSettings.AmazonS3SecretAccessKey = React.findDOMNode(this.refs.AmazonS3SecretAccessKey).value;
+ config.FileSettings.AmazonS3Bucket = React.findDOMNode(this.refs.AmazonS3Bucket).value;
+ config.FileSettings.AmazonS3Region = React.findDOMNode(this.refs.AmazonS3Region).value;
+ config.FileSettings.EnablePublicLink = React.findDOMNode(this.refs.EnablePublicLink).checked;
+
+ config.FileSettings.PublicLinkSalt = React.findDOMNode(this.refs.PublicLinkSalt).value.trim();
+
+ if (config.FileSettings.PublicLinkSalt === '') {
+ config.FileSettings.PublicLinkSalt = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ React.findDOMNode(this.refs.PublicLinkSalt).value = config.FileSettings.PublicLinkSalt;
+ }
+
+ var thumbnailWidth = 120;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.ThumbnailWidth).value, 10))) {
+ thumbnailWidth = parseInt(React.findDOMNode(this.refs.ThumbnailWidth).value, 10);
+ }
+ config.FileSettings.ThumbnailWidth = thumbnailWidth;
+ React.findDOMNode(this.refs.ThumbnailWidth).value = thumbnailWidth;
+
+ var thumbnailHeight = 100;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.ThumbnailHeight).value, 10))) {
+ thumbnailHeight = parseInt(React.findDOMNode(this.refs.ThumbnailHeight).value, 10);
+ }
+ config.FileSettings.ThumbnailHeight = thumbnailHeight;
+ React.findDOMNode(this.refs.ThumbnailHeight).value = thumbnailHeight;
+
+ var previewWidth = 1024;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.PreviewWidth).value, 10))) {
+ previewWidth = parseInt(React.findDOMNode(this.refs.PreviewWidth).value, 10);
+ }
+ config.FileSettings.PreviewWidth = previewWidth;
+ React.findDOMNode(this.refs.PreviewWidth).value = previewWidth;
+
+ var previewHeight = 0;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.PreviewHeight).value, 10))) {
+ previewHeight = parseInt(React.findDOMNode(this.refs.PreviewHeight).value, 10);
+ }
+ config.FileSettings.PreviewHeight = previewHeight;
+ React.findDOMNode(this.refs.PreviewHeight).value = previewHeight;
+
+ var profileWidth = 128;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.ProfileWidth).value, 10))) {
+ profileWidth = parseInt(React.findDOMNode(this.refs.ProfileWidth).value, 10);
+ }
+ config.FileSettings.ProfileWidth = profileWidth;
+ React.findDOMNode(this.refs.ProfileWidth).value = profileWidth;
+
+ var profileHeight = 128;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.ProfileHeight).value, 10))) {
+ profileHeight = parseInt(React.findDOMNode(this.refs.ProfileHeight).value, 10);
+ }
+ config.FileSettings.ProfileHeight = profileHeight;
+ React.findDOMNode(this.refs.ProfileHeight).value = profileHeight;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ var enableFile = false;
+ var enableS3 = false;
+
+ if (this.state.DriverName === 'local') {
+ enableFile = true;
+ }
+
+ if (this.state.DriverName === 'amazons3') {
+ enableS3 = true;
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+ <h3>{'File Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='DriverName'
+ >
+ {'Store Files In:'}
+ </label>
+ <div className='col-sm-8'>
+ <select
+ className='form-control'
+ id='DriverName'
+ ref='DriverName'
+ defaultValue={this.props.config.FileSettings.DriverName}
+ onChange={this.handleChange.bind(this, 'DriverName')}
+ >
+ <option value=''>{'Disable File Storage'}</option>
+ <option value='local'>{'Local File System'}</option>
+ <option value='amazons3'>{'Amazon S3'}</option>
+ </select>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Directory'
+ >
+ {'Local Directory Location:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='Directory'
+ ref='Directory'
+ placeholder='Ex "./data/"'
+ defaultValue={this.props.config.FileSettings.Directory}
+ onChange={this.handleChange}
+ disabled={!enableFile}
+ />
+ <p className='help-text'>{'Directory to which image files are written. If blank, will be set to ./data/.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AmazonS3AccessKeyId'
+ >
+ {'Amazon S3 Access Key Id:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AmazonS3AccessKeyId'
+ ref='AmazonS3AccessKeyId'
+ placeholder='Ex "AKIADTOVBGERKLCBV"'
+ defaultValue={this.props.config.FileSettings.AmazonS3AccessKeyId}
+ onChange={this.handleChange}
+ disabled={!enableS3}
+ />
+ <p className='help-text'>{'Obtain this credential from your Amazon EC2 administrator.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AmazonS3SecretAccessKey'
+ >
+ {'Amazon S3 Secret Access Key:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AmazonS3SecretAccessKey'
+ ref='AmazonS3SecretAccessKey'
+ placeholder='Ex "jcuS8PuvcpGhpgHhlcpT1Mx42pnqMxQY"'
+ defaultValue={this.props.config.FileSettings.AmazonS3SecretAccessKey}
+ onChange={this.handleChange}
+ disabled={!enableS3}
+ />
+ <p className='help-text'>{'Obtain this credential from your Amazon EC2 administrator.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AmazonS3Bucket'
+ >
+ {'Amazon S3 Bucket:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AmazonS3Bucket'
+ ref='AmazonS3Bucket'
+ placeholder='Ex "mattermost-media"'
+ defaultValue={this.props.config.FileSettings.AmazonS3Bucket}
+ onChange={this.handleChange}
+ disabled={!enableS3}
+ />
+ <p className='help-text'>{'Name you selected for your S3 bucket in AWS.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AmazonS3Region'
+ >
+ {'Amazon S3 Region:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AmazonS3Region'
+ ref='AmazonS3Region'
+ placeholder='Ex "us-east-1"'
+ defaultValue={this.props.config.FileSettings.AmazonS3Region}
+ onChange={this.handleChange}
+ disabled={!enableS3}
+ />
+ <p className='help-text'>{'AWS region you selected for creating your S3 bucket.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ThumbnailWidth'
+ >
+ {'Thumbnail Width:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='ThumbnailWidth'
+ ref='ThumbnailWidth'
+ placeholder='Ex "120"'
+ defaultValue={this.props.config.FileSettings.ThumbnailWidth}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Width of thumbnails generated from uploaded images. Updating this value changes how thumbnail images render in future, but does not change images created in the past.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ThumbnailHeight'
+ >
+ {'Thumbnail Height:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='ThumbnailHeight'
+ ref='ThumbnailHeight'
+ placeholder='Ex "100"'
+ defaultValue={this.props.config.FileSettings.ThumbnailHeight}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Height of thumbnails generated from uploaded images. Updating this value changes how thumbnail images render in future, but does not change images created in the past.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='PreviewWidth'
+ >
+ {'Preview Width:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='PreviewWidth'
+ ref='PreviewWidth'
+ placeholder='Ex "1024"'
+ defaultValue={this.props.config.FileSettings.PreviewWidth}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Maximum width of preview image. Updating this value changes how preview images render in future, but does not change images created in the past.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='PreviewHeight'
+ >
+ {'Preview Height:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='PreviewHeight'
+ ref='PreviewHeight'
+ placeholder='Ex "0"'
+ defaultValue={this.props.config.FileSettings.PreviewHeight}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Maximum height of preview image ("0": Sets to auto-size). Updating this value changes how preview images render in future, but does not change images created in the past.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ProfileWidth'
+ >
+ {'Profile Width:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='ProfileWidth'
+ ref='ProfileWidth'
+ placeholder='Ex "1024"'
+ defaultValue={this.props.config.FileSettings.ProfileWidth}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Width of profile picture.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ProfileHeight'
+ >
+ {'Profile Height:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='ProfileHeight'
+ ref='ProfileHeight'
+ placeholder='Ex "0"'
+ defaultValue={this.props.config.FileSettings.ProfileHeight}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Height of profile picture.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnablePublicLink'
+ >
+ {'Share Public File Link: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnablePublicLink'
+ value='true'
+ ref='EnablePublicLink'
+ defaultChecked={this.props.config.FileSettings.EnablePublicLink}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnablePublicLink'
+ value='false'
+ defaultChecked={!this.props.config.FileSettings.EnablePublicLink}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'Allow users to share public links to files and images.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='PublicLinkSalt'
+ >
+ {'Public Link Salt:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='PublicLinkSalt'
+ ref='PublicLinkSalt'
+ placeholder='Ex "gxHVDcKUyP2y1eiyW8S8na1UYQAfq6J6"'
+ defaultValue={this.props.config.FileSettings.PublicLinkSalt}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'32-character salt added to signing of public image links. Randomly generated on install. Click "Re-Generate" to create new salt.'}</p>
+ <div className='help-text'>
+ <button
+ className='help-link'
+ onClick={this.handleGenerate}
+ >
+ {'Re-Generate'}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+FileSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/log_settings.jsx b/web/react/components/admin_console/log_settings.jsx
index 4e3db8f68..1c39c60e8 100644
--- a/web/react/components/admin_console/log_settings.jsx
+++ b/web/react/components/admin_console/log_settings.jsx
@@ -12,13 +12,33 @@ export default class LogSettings extends React.Component {
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
+ consoleEnable: this.props.config.LogSettings.EnableConsole,
+ fileEnable: this.props.config.LogSettings.EnableFile,
saveNeeded: false,
serverError: null
};
}
- handleChange() {
- this.setState({saveNeeded: true, serverError: this.state.serverError});
+ handleChange(action) {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ if (action === 'console_true') {
+ s.consoleEnable = true;
+ }
+
+ if (action === 'console_false') {
+ s.consoleEnable = false;
+ }
+
+ if (action === 'file_true') {
+ s.fileEnable = true;
+ }
+
+ if (action === 'file_false') {
+ s.fileEnable = false;
+ }
+
+ this.setState(s);
}
handleSubmit(e) {
@@ -26,9 +46,9 @@ export default class LogSettings extends React.Component {
$('#save-button').button('loading');
var config = this.props.config;
- config.LogSettings.ConsoleEnable = React.findDOMNode(this.refs.consoleEnable).checked;
+ config.LogSettings.EnableConsole = React.findDOMNode(this.refs.consoleEnable).checked;
config.LogSettings.ConsoleLevel = React.findDOMNode(this.refs.consoleLevel).value;
- config.LogSettings.FileEnable = React.findDOMNode(this.refs.fileEnable).checked;
+ config.LogSettings.EnableFile = React.findDOMNode(this.refs.fileEnable).checked;
config.LogSettings.FileLevel = React.findDOMNode(this.refs.fileLevel).value;
config.LogSettings.FileLocation = React.findDOMNode(this.refs.fileLocation).value.trim();
config.LogSettings.FileFormat = React.findDOMNode(this.refs.fileFormat).value.trim();
@@ -37,11 +57,21 @@ export default class LogSettings extends React.Component {
config,
() => {
AsyncClient.getConfig();
- this.setState({serverError: null, saveNeeded: false});
+ this.setState({
+ consoleEnable: config.LogSettings.EnableConsole,
+ fileEnable: config.LogSettings.EnableFile,
+ serverError: null,
+ saveNeeded: false
+ });
$('#save-button').button('reset');
},
(err) => {
- this.setState({serverError: err.message, saveNeeded: true});
+ this.setState({
+ consoleEnable: config.LogSettings.EnableConsole,
+ fileEnable: config.LogSettings.EnableFile,
+ serverError: err.message,
+ saveNeeded: true
+ });
$('#save-button').button('reset');
}
);
@@ -71,7 +101,7 @@ export default class LogSettings extends React.Component {
className='control-label col-sm-4'
htmlFor='consoleEnable'
>
- {'Log To the Console: '}
+ {'Log To The Console: '}
</label>
<div className='col-sm-8'>
<label className='radio-inline'>
@@ -80,8 +110,8 @@ export default class LogSettings extends React.Component {
name='consoleEnable'
value='true'
ref='consoleEnable'
- defaultChecked={this.props.config.LogSettings.ConsoleEnable}
- onChange={this.handleChange}
+ defaultChecked={this.props.config.LogSettings.EnableConsole}
+ onChange={this.handleChange.bind(this, 'console_true')}
/>
{'true'}
</label>
@@ -90,12 +120,12 @@ export default class LogSettings extends React.Component {
type='radio'
name='consoleEnable'
value='false'
- defaultChecked={!this.props.config.LogSettings.ConsoleEnable}
- onChange={this.handleChange}
+ defaultChecked={!this.props.config.LogSettings.EnableConsole}
+ onChange={this.handleChange.bind(this, 'console_false')}
/>
{'false'}
</label>
- <p className='help-text'>{'Typically set to false in production. Developers may set this field to true to output log messages to console based on the console level option. If true then the server will output messages to the standard output stream (stdout).'}</p>
+ <p className='help-text'>{'Typically set to false in production. Developers may set this field to true to output log messages to console based on the console level option. If true, server writes messages to the standard output stream (stdout).'}</p>
</div>
</div>
@@ -113,12 +143,13 @@ export default class LogSettings extends React.Component {
ref='consoleLevel'
defaultValue={this.props.config.LogSettings.consoleLevel}
onChange={this.handleChange}
+ disabled={!this.state.consoleEnable}
>
<option value='DEBUG'>{'DEBUG'}</option>
<option value='INFO'>{'INFO'}</option>
<option value='ERROR'>{'ERROR'}</option>
</select>
- <p className='help-text'>{'This setting determines the level of detail at which log events are written to the console. ERROR: Outputs only error messages. INFO: Outputs error messages and information around startup and initialization. DEBUG: Prints high detail for developers debugging issues working on debugging issues.'}</p>
+ <p className='help-text'>{'This setting determines the level of detail at which log events are written to the console. ERROR: Outputs only error messages. INFO: Outputs error messages and information around startup and initialization. DEBUG: Prints high detail for developers working on debugging issues.'}</p>
</div>
</div>
@@ -135,8 +166,8 @@ export default class LogSettings extends React.Component {
name='fileEnable'
ref='fileEnable'
value='true'
- defaultChecked={this.props.config.LogSettings.FileEnable}
- onChange={this.handleChange}
+ defaultChecked={this.props.config.LogSettings.EnableFile}
+ onChange={this.handleChange.bind(this, 'file_true')}
/>
{'true'}
</label>
@@ -145,12 +176,12 @@ export default class LogSettings extends React.Component {
type='radio'
name='fileEnable'
value='false'
- defaultChecked={!this.props.config.LogSettings.FileEnable}
- onChange={this.handleChange}
+ defaultChecked={!this.props.config.LogSettings.EnableFile}
+ onChange={this.handleChange.bind(this, 'file_false')}
/>
{'false'}
</label>
- <p className='help-text'>{'Typically set to true in production. When true log files are written to the file specified in file location field below.'}</p>
+ <p className='help-text'>{'Typically set to true in production. When true, log files are written to the log file specified in file location field below.'}</p>
</div>
</div>
@@ -168,12 +199,13 @@ export default class LogSettings extends React.Component {
ref='fileLevel'
defaultValue={this.props.config.LogSettings.FileLevel}
onChange={this.handleChange}
+ disabled={!this.state.fileEnable}
>
<option value='DEBUG'>{'DEBUG'}</option>
<option value='INFO'>{'INFO'}</option>
<option value='ERROR'>{'ERROR'}</option>
</select>
- <p className='help-text'>{'This setting determines the level of detail at which log events are written to the file. ERROR: Outputs only error messages. INFO: Outputs error messages and information around startup and initialization. DEBUG: Prints high detail for developers debugging issues working on debugging issues.'}</p>
+ <p className='help-text'>{'This setting determines the level of detail at which log events are written to the log file. ERROR: Outputs only error messages. INFO: Outputs error messages and information around startup and initialization. DEBUG: Prints high detail for developers working on debugging issues.'}</p>
</div>
</div>
@@ -193,8 +225,9 @@ export default class LogSettings extends React.Component {
placeholder='Enter your file location'
defaultValue={this.props.config.LogSettings.FileLocation}
onChange={this.handleChange}
+ disabled={!this.state.fileEnable}
/>
- <p className='help-text'>{'File to which log files are written. If blank, will be set to ./logs/mattermost.log. Log rotation is enabled and new files may be created in the same directory.'}</p>
+ <p className='help-text'>{'File to which log files are written. If blank, will be set to ./logs/mattermost, which writes logs to mattermost.log. Log rotation is enabled and every 10,000 lines of log information is written to new files stored in the same directory, for example mattermost.2015-09-23.001, mattermost.2015-09-23.002, and so forth.'}</p>
</div>
</div>
@@ -214,6 +247,7 @@ export default class LogSettings extends React.Component {
placeholder='Enter your file format'
defaultValue={this.props.config.LogSettings.FileFormat}
onChange={this.handleChange}
+ disabled={!this.state.fileEnable}
/>
<p className='help-text'>
{'Format of log message output. If blank will be set to "[%D %T] [%L] %M", where:'}
diff --git a/web/react/components/admin_console/privacy_settings.jsx b/web/react/components/admin_console/privacy_settings.jsx
new file mode 100644
index 000000000..affd8ae11
--- /dev/null
+++ b/web/react/components/admin_console/privacy_settings.jsx
@@ -0,0 +1,163 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+
+export default class PrivacySettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+
+ this.state = {
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange() {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.PrivacySettings.ShowEmailAddress = React.findDOMNode(this.refs.ShowEmailAddress).checked;
+ config.PrivacySettings.ShowFullName = React.findDOMNode(this.refs.ShowFullName).checked;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+ <h3>{'Privacy Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ShowEmailAddress'
+ >
+ {'Show Email Address: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='ShowEmailAddress'
+ value='true'
+ ref='ShowEmailAddress'
+ defaultChecked={this.props.config.PrivacySettings.ShowEmailAddress}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='ShowEmailAddress'
+ value='false'
+ defaultChecked={!this.props.config.PrivacySettings.ShowEmailAddress}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When false, hides email address of users from other users in the user interface, including team owners and team administrators. Used when system is set up for managing teams where some users choose to keep their contact information private.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ShowFullName'
+ >
+ {'Show Full Name: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='ShowFullName'
+ value='true'
+ ref='ShowFullName'
+ defaultChecked={this.props.config.PrivacySettings.ShowFullName}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='ShowFullName'
+ value='false'
+ defaultChecked={!this.props.config.PrivacySettings.ShowFullName}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When false, hides full name of users from other users including team owner and team administrators.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+PrivacySettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/rate_settings.jsx b/web/react/components/admin_console/rate_settings.jsx
new file mode 100644
index 000000000..0081daca3
--- /dev/null
+++ b/web/react/components/admin_console/rate_settings.jsx
@@ -0,0 +1,272 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+
+export default class RateSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+
+ this.state = {
+ EnableRateLimiter: this.props.config.RateLimitSettings.EnableRateLimiter,
+ VaryByRemoteAddr: this.props.config.RateLimitSettings.VaryByRemoteAddr,
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange(action) {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+
+ if (action === 'EnableRateLimiterTrue') {
+ s.EnableRateLimiter = true;
+ }
+
+ if (action === 'EnableRateLimiterFalse') {
+ s.EnableRateLimiter = false;
+ }
+
+ if (action === 'VaryByRemoteAddrTrue') {
+ s.VaryByRemoteAddr = true;
+ }
+
+ if (action === 'VaryByRemoteAddrFalse') {
+ s.VaryByRemoteAddr = false;
+ }
+
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.RateLimitSettings.EnableRateLimiter = React.findDOMNode(this.refs.EnableRateLimiter).checked;
+ config.RateLimitSettings.VaryByRemoteAddr = React.findDOMNode(this.refs.VaryByRemoteAddr).checked;
+ config.RateLimitSettings.VaryByHeader = React.findDOMNode(this.refs.VaryByHeader).value.trim();
+
+ var PerSec = 10;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.PerSec).value, 10))) {
+ PerSec = parseInt(React.findDOMNode(this.refs.PerSec).value, 10);
+ }
+ config.RateLimitSettings.PerSec = PerSec;
+ React.findDOMNode(this.refs.PerSec).value = PerSec;
+
+ var MemoryStoreSize = 10000;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.MemoryStoreSize).value, 10))) {
+ MemoryStoreSize = parseInt(React.findDOMNode(this.refs.MemoryStoreSize).value, 10);
+ }
+ config.RateLimitSettings.MemoryStoreSize = MemoryStoreSize;
+ React.findDOMNode(this.refs.MemoryStoreSize).value = MemoryStoreSize;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+
+ <div className='banner'>
+ <div className='banner__content'>
+ <h4 className='banner__heading'>{'Note:'}</h4>
+ <p>{'Changing properties in this section will require a server restart before taking effect.'}</p>
+ </div>
+ </div>
+
+ <h3>{'Rate Limit Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnableRateLimiter'
+ >
+ {'Enable Rate Limiter: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableRateLimiter'
+ value='true'
+ ref='EnableRateLimiter'
+ defaultChecked={this.props.config.RateLimitSettings.EnableRateLimiter}
+ onChange={this.handleChange.bind(this, 'EnableRateLimiterTrue')}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableRateLimiter'
+ value='false'
+ defaultChecked={!this.props.config.RateLimitSettings.EnableRateLimiter}
+ onChange={this.handleChange.bind(this, 'EnableRateLimiterFalse')}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When true, APIs are throttled at rates specified below.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='PerSec'
+ >
+ {'Number Of Queries Per Second:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='PerSec'
+ ref='PerSec'
+ placeholder='Ex "10"'
+ defaultValue={this.props.config.RateLimitSettings.PerSec}
+ onChange={this.handleChange}
+ disabled={!this.state.EnableRateLimiter}
+ />
+ <p className='help-text'>{'Throttles API at this number of requests per second.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='MemoryStoreSize'
+ >
+ {'Memory Store Size:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='MemoryStoreSize'
+ ref='MemoryStoreSize'
+ placeholder='Ex "10000"'
+ defaultValue={this.props.config.RateLimitSettings.MemoryStoreSize}
+ onChange={this.handleChange}
+ disabled={!this.state.EnableRateLimiter}
+ />
+ <p className='help-text'>{'Maximum number of users sessions connected to the system as determined by "Vary By Remote Address" and "Vary By Header" settings below.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='VaryByRemoteAddr'
+ >
+ {'Vary By Remote Address: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='VaryByRemoteAddr'
+ value='true'
+ ref='VaryByRemoteAddr'
+ defaultChecked={this.props.config.RateLimitSettings.VaryByRemoteAddr}
+ onChange={this.handleChange.bind(this, 'VaryByRemoteAddrTrue')}
+ disabled={!this.state.EnableRateLimiter}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='VaryByRemoteAddr'
+ value='false'
+ defaultChecked={!this.props.config.RateLimitSettings.VaryByRemoteAddr}
+ onChange={this.handleChange.bind(this, 'VaryByRemoteAddrFalse')}
+ disabled={!this.state.EnableRateLimiter}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When true, rate limit API access by IP address.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='VaryByHeader'
+ >
+ {'Vary By HTTP Header:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='VaryByHeader'
+ ref='VaryByHeader'
+ placeholder='Ex "X-Real-IP", "X-Forwarded-For"'
+ defaultValue={this.props.config.RateLimitSettings.VaryByHeader}
+ onChange={this.handleChange}
+ disabled={!this.state.EnableRateLimiter || this.state.VaryByRemoteAddr}
+ />
+ <p className='help-text'>{'When filled in, vary rate limiting by HTTP header field specified (e.g. when configuring Ngnix set to "X-Real-IP", when configuring AmazonELB set to "X-Forwarded-For").'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+RateSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/reset_password_modal.jsx b/web/react/components/admin_console/reset_password_modal.jsx
new file mode 100644
index 000000000..0b83edb17
--- /dev/null
+++ b/web/react/components/admin_console/reset_password_modal.jsx
@@ -0,0 +1,132 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var Modal = ReactBootstrap.Modal;
+
+export default class ResetPasswordModal extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.doSubmit = this.doSubmit.bind(this);
+ this.doCancel = this.doCancel.bind(this);
+
+ this.state = {
+ serverError: null
+ };
+ }
+
+ doSubmit(e) {
+ e.preventDefault();
+ var password = React.findDOMNode(this.refs.password).value;
+
+ if (!password || password.length < 5) {
+ this.setState({serverError: 'Please enter at least 5 characters.'});
+ return;
+ }
+
+ this.setState({serverError: null});
+
+ var data = {};
+ data.new_password = password;
+ data.name = this.props.team.name;
+ data.user_id = this.props.user.id;
+
+ Client.resetPassword(data,
+ () => {
+ this.props.onModalSubmit(React.findDOMNode(this.refs.password).value);
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ doCancel() {
+ this.setState({serverError: null});
+ this.props.onModalDismissed();
+ }
+
+ render() {
+ if (this.props.user == null) {
+ return <div/>;
+ }
+
+ let urlClass = 'input-group input-group--limit';
+ let serverError = null;
+
+ if (this.state.serverError) {
+ urlClass += ' has-error';
+ serverError = <div className='form-group has-error'><p className='input__help error'>{this.state.serverError}</p></div>;
+ }
+
+ return (
+ <Modal
+ show={this.props.show}
+ onHide={this.doCancel}
+ >
+ <Modal.Header closeButton={true}>
+ <Modal.Title>{'Reset Password'}</Modal.Title>
+ </Modal.Header>
+ <form
+ role='form'
+ className='form-horizontal'
+ >
+ <Modal.Body>
+ <div className='form-group'>
+ <div className='col-sm-10'>
+ <div className={urlClass}>
+ <span
+ data-toggle='tooltip'
+ title='New Password'
+ className='input-group-addon'
+ >
+ {'New Password'}
+ </span>
+ <input
+ type='password'
+ ref='password'
+ className='form-control'
+ maxLength='22'
+ autoFocus={true}
+ tabIndex='1'
+ />
+ </div>
+ {serverError}
+ </div>
+ </div>
+ </Modal.Body>
+ <Modal.Footer>
+ <button
+ type='button'
+ className='btn btn-default'
+ onClick={this.doCancel}
+ >
+ {'Close'}
+ </button>
+ <button
+ onClick={this.doSubmit}
+ type='submit'
+ className='btn btn-primary'
+ tabIndex='2'
+ >
+ {'Select'}
+ </button>
+ </Modal.Footer>
+ </form>
+ </Modal>
+ );
+ }
+}
+
+ResetPasswordModal.defaultProps = {
+ show: false
+};
+
+ResetPasswordModal.propTypes = {
+ user: React.PropTypes.object,
+ team: React.PropTypes.object,
+ show: React.PropTypes.bool.isRequired,
+ onModalSubmit: React.PropTypes.func,
+ onModalDismissed: React.PropTypes.func
+};
diff --git a/web/react/components/admin_console/select_team_modal.jsx b/web/react/components/admin_console/select_team_modal.jsx
index fa30de7b2..343f65131 100644
--- a/web/react/components/admin_console/select_team_modal.jsx
+++ b/web/react/components/admin_console/select_team_modal.jsx
@@ -1,124 +1,99 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-export default class SelectTeam extends React.Component {
+var Modal = ReactBootstrap.Modal;
+
+export default class SelectTeamModal extends React.Component {
constructor(props) {
super(props);
- this.state = {
- };
+ this.doSubmit = this.doSubmit.bind(this);
+ this.doCancel = this.doCancel.bind(this);
}
+ doSubmit(e) {
+ e.preventDefault();
+ this.props.onModalSubmit(React.findDOMNode(this.refs.team).value);
+ }
+ doCancel() {
+ this.props.onModalDismissed();
+ }
render() {
+ if (this.props.teams == null) {
+ return <div/>;
+ }
+
+ var options = [];
+
+ for (var key in this.props.teams) {
+ if (this.props.teams.hasOwnProperty(key)) {
+ var team = this.props.teams[key];
+ options.push(
+ <option
+ key={'opt_' + team.id}
+ value={team.id}
+ >
+ {team.name}
+ </option>
+ );
+ }
+ }
+
return (
- <div className='modal fade'
- id='select-team'
- tabIndex='-1'
- role='dialog'
- aria-labelledby='teamsModalLabel'
+ <Modal
+ show={this.props.show}
+ onHide={this.doCancel}
>
- <div className='modal-dialog'
- role='document'
+ <Modal.Header closeButton={true}>
+ <Modal.Title>{'Select Team'}</Modal.Title>
+ </Modal.Header>
+ <form
+ role='form'
+ className='form-horizontal'
>
- <div className='modal-content'>
- <div className='modal-header'>
- <button
- type='button'
- className='close'
- data-dismiss='modal'
- aria-label='Close'
- >
- <span aria-hidden='true'>&times;</span>
- </button>
- <h4
- className='modal-title'
- id='teamsModalLabel'
- >
- {'Select a team'}
- </h4>
- </div>
- <div className='modal-body'>
- <table className='more-channel-table table'>
- <tbody>
- <tr>
- <td>
- <p className='more-channel-name'>{'Descartes'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Grouping'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Adventure'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Crossroads'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Sky scraping'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Outdoors'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Microsoft'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- <tr>
- <td>
- <p className='more-channel-name'>{'Apple'}</p>
- </td>
- <td className='td--action'>
- <button className='btn btn-primary'>{'Join'}</button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- <div className='modal-footer'>
- <button
- type='button'
- className='btn btn-default'
- data-dismiss='modal'
- >
- {'Close'}
- </button>
+ <Modal.Body>
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ <select
+ ref='team'
+ size='10'
+ style={{width: '100%'}}
+ >
+ {options}
+ </select>
+ </div>
</div>
- </div>
- </div>
- </div>
+ </Modal.Body>
+ <Modal.Footer>
+ <button
+ type='button'
+ className='btn btn-default'
+ onClick={this.doCancel}
+ >
+ {'Close'}
+ </button>
+ <button
+ onClick={this.doSubmit}
+ type='submit'
+ className='btn btn-primary'
+ tabIndex='2'
+ >
+ {'Select'}
+ </button>
+ </Modal.Footer>
+ </form>
+ </Modal>
);
}
-} \ No newline at end of file
+}
+
+SelectTeamModal.defaultProps = {
+ show: false
+};
+
+SelectTeamModal.propTypes = {
+ teams: React.PropTypes.object,
+ show: React.PropTypes.bool.isRequired,
+ onModalSubmit: React.PropTypes.func,
+ onModalDismissed: React.PropTypes.func
+};
diff --git a/web/react/components/admin_console/service_settings.jsx b/web/react/components/admin_console/service_settings.jsx
new file mode 100644
index 000000000..245ffa871
--- /dev/null
+++ b/web/react/components/admin_console/service_settings.jsx
@@ -0,0 +1,296 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+
+export default class ServiceSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+
+ this.state = {
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange() {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.ServiceSettings.ListenAddress = React.findDOMNode(this.refs.ListenAddress).value.trim();
+ if (config.ServiceSettings.ListenAddress === '') {
+ config.ServiceSettings.ListenAddress = ':8065';
+ React.findDOMNode(this.refs.ListenAddress).value = config.ServiceSettings.ListenAddress;
+ }
+
+ config.ServiceSettings.SegmentDeveloperKey = React.findDOMNode(this.refs.SegmentDeveloperKey).value.trim();
+ config.ServiceSettings.GoogleDeveloperKey = React.findDOMNode(this.refs.GoogleDeveloperKey).value.trim();
+ //config.ServiceSettings.EnableOAuthServiceProvider = React.findDOMNode(this.refs.EnableOAuthServiceProvider).checked;
+ config.ServiceSettings.EnableIncomingWebhooks = React.findDOMNode(this.refs.EnableIncomingWebhooks).checked;
+ config.ServiceSettings.EnableTesting = React.findDOMNode(this.refs.EnableTesting).checked;
+
+ var MaximumLoginAttempts = 10;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.MaximumLoginAttempts).value, 10))) {
+ MaximumLoginAttempts = parseInt(React.findDOMNode(this.refs.MaximumLoginAttempts).value, 10);
+ }
+ config.ServiceSettings.MaximumLoginAttempts = MaximumLoginAttempts;
+ React.findDOMNode(this.refs.MaximumLoginAttempts).value = MaximumLoginAttempts;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+
+ <h3>{'Service Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='ListenAddress'
+ >
+ {'Listen Address:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='ListenAddress'
+ ref='ListenAddress'
+ placeholder='Ex ":8065"'
+ defaultValue={this.props.config.ServiceSettings.ListenAddress}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'The address to which to bind and listen. Entering ":8065" will bind to all interfaces or you can choose one like "127.0.0.1:8065". Changing this will require a server restart before taking effect.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='MaximumLoginAttempts'
+ >
+ {'Maximum Login Attempts:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='MaximumLoginAttempts'
+ ref='MaximumLoginAttempts'
+ placeholder='Ex "10"'
+ defaultValue={this.props.config.ServiceSettings.MaximumLoginAttempts}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Login attempts allowed before user is locked out and required to reset password via email.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='SegmentDeveloperKey'
+ >
+ {'Segment Developer Key:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='SegmentDeveloperKey'
+ ref='SegmentDeveloperKey'
+ placeholder='Ex "g3fgGOXJAQ43QV7rAh6iwQCkV4cA1Gs"'
+ defaultValue={this.props.config.ServiceSettings.SegmentDeveloperKey}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'For users running a SaaS services, sign up for a key at Segment.com to track metrics.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='GoogleDeveloperKey'
+ >
+ {'Google Developer Key:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='GoogleDeveloperKey'
+ ref='GoogleDeveloperKey'
+ placeholder='Ex "7rAh6iwQCkV4cA1Gsg3fgGOXJAQ43QV"'
+ defaultValue={this.props.config.ServiceSettings.GoogleDeveloperKey}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Set this key to enable embedding of YouTube video previews based on hyperlinks appearing in messages or comments. Instructions to obtain a key available at '}<a href='https://www.youtube.com/watch?v=Im69kzhpR3I'>{'https://www.youtube.com/watch?v=Im69kzhpR3I'}</a>{'. Leaving field blank disables the automatic generation of YouTube video previews from links.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnableIncomingWebhooks'
+ >
+ {'Enable Incoming Webhooks: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableIncomingWebhooks'
+ value='true'
+ ref='EnableIncomingWebhooks'
+ defaultChecked={this.props.config.ServiceSettings.EnableIncomingWebhooks}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableIncomingWebhooks'
+ value='false'
+ defaultChecked={!this.props.config.ServiceSettings.EnableIncomingWebhooks}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When true, incoming webhooks will be allowed.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnableTesting'
+ >
+ {'Enable Testing: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableTesting'
+ value='true'
+ ref='EnableTesting'
+ defaultChecked={this.props.config.ServiceSettings.EnableTesting}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableTesting'
+ value='false'
+ defaultChecked={!this.props.config.ServiceSettings.EnableTesting}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'(Developer Option) When true, /loadtest slash command is enabled to load test accounts and test data. Changing this will require a server restart before taking effect.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+// <div className='form-group'>
+// <label
+// className='control-label col-sm-4'
+// htmlFor='EnableOAuthServiceProvider'
+// >
+// {'Enable OAuth Service Provider: '}
+// </label>
+// <div className='col-sm-8'>
+// <label className='radio-inline'>
+// <input
+// type='radio'
+// name='EnableOAuthServiceProvider'
+// value='true'
+// ref='EnableOAuthServiceProvider'
+// defaultChecked={this.props.config.ServiceSettings.EnableOAuthServiceProvider}
+// onChange={this.handleChange}
+// />
+// {'true'}
+// </label>
+// <label className='radio-inline'>
+// <input
+// type='radio'
+// name='EnableOAuthServiceProvider'
+// value='false'
+// defaultChecked={!this.props.config.ServiceSettings.EnableOAuthServiceProvider}
+// onChange={this.handleChange}
+// />
+// {'false'}
+// </label>
+// <p className='help-text'>{'When enabled Mattermost will act as an OAuth2 Provider. Changing this will require a server restart before taking effect.'}</p>
+// </div>
+// </div>
+
+ServiceSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/sql_settings.jsx b/web/react/components/admin_console/sql_settings.jsx
new file mode 100644
index 000000000..430a7453b
--- /dev/null
+++ b/web/react/components/admin_console/sql_settings.jsx
@@ -0,0 +1,283 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var crypto = require('crypto');
+
+export default class SqlSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.handleGenerate = this.handleGenerate.bind(this);
+
+ this.state = {
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange() {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.SqlSettings.Trace = React.findDOMNode(this.refs.Trace).checked;
+ config.SqlSettings.AtRestEncryptKey = React.findDOMNode(this.refs.AtRestEncryptKey).value.trim();
+
+ if (config.SqlSettings.AtRestEncryptKey === '') {
+ config.SqlSettings.AtRestEncryptKey = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ React.findDOMNode(this.refs.AtRestEncryptKey).value = config.SqlSettings.AtRestEncryptKey;
+ }
+
+ var MaxOpenConns = 10;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.MaxOpenConns).value, 10))) {
+ MaxOpenConns = parseInt(React.findDOMNode(this.refs.MaxOpenConns).value, 10);
+ }
+ config.SqlSettings.MaxOpenConns = MaxOpenConns;
+ React.findDOMNode(this.refs.MaxOpenConns).value = MaxOpenConns;
+
+ var MaxIdleConns = 10;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.MaxIdleConns).value, 10))) {
+ MaxIdleConns = parseInt(React.findDOMNode(this.refs.MaxIdleConns).value, 10);
+ }
+ config.SqlSettings.MaxIdleConns = MaxIdleConns;
+ React.findDOMNode(this.refs.MaxIdleConns).value = MaxIdleConns;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ handleGenerate(e) {
+ e.preventDefault();
+ React.findDOMNode(this.refs.AtRestEncryptKey).value = crypto.randomBytes(256).toString('base64').substring(0, 32);
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ var dataSource = '**********' + this.props.config.SqlSettings.DataSource.substring(this.props.config.SqlSettings.DataSource.indexOf('@'));
+
+ var dataSourceReplicas = '';
+ this.props.config.SqlSettings.DataSourceReplicas.forEach((replica) => {
+ dataSourceReplicas += '[**********' + replica.substring(replica.indexOf('@')) + '] ';
+ });
+
+ if (this.props.config.SqlSettings.DataSourceReplicas.length === 0) {
+ dataSourceReplicas = 'none';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+
+ <div className='banner'>
+ <div className='banner__content'>
+ <h4 className='banner__heading'>{'Note:'}</h4>
+ <p>{'Changing properties in this section will require a server restart before taking effect.'}</p>
+ </div>
+ </div>
+
+ <h3>{'SQL Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='DriverName'
+ >
+ {'Driver Name:'}
+ </label>
+ <div className='col-sm-8'>
+ <p className='help-text'>{this.props.config.SqlSettings.DriverName}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='DataSource'
+ >
+ {'Data Source:'}
+ </label>
+ <div className='col-sm-8'>
+ <p className='help-text'>{dataSource}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='DataSourceReplicas'
+ >
+ {'Data Source Replicas:'}
+ </label>
+ <div className='col-sm-8'>
+ <p className='help-text'>{dataSourceReplicas}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='MaxIdleConns'
+ >
+ {'Maximum Idle Connections:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='MaxIdleConns'
+ ref='MaxIdleConns'
+ placeholder='Ex "10"'
+ defaultValue={this.props.config.SqlSettings.MaxIdleConns}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Maximum number of idle connections held open to the database.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='MaxOpenConns'
+ >
+ {'Maximum Open Connections:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='MaxOpenConns'
+ ref='MaxOpenConns'
+ placeholder='Ex "10"'
+ defaultValue={this.props.config.SqlSettings.MaxOpenConns}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Maximum number of open connections held open to the database.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='AtRestEncryptKey'
+ >
+ {'At Rest Encrypt Key:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='AtRestEncryptKey'
+ ref='AtRestEncryptKey'
+ placeholder='Ex "gxHVDcKUyP2y1eiyW8S8na1UYQAfq6J6"'
+ defaultValue={this.props.config.SqlSettings.AtRestEncryptKey}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'32-character salt available to encrypt and decrypt sensitive fields in database.'}</p>
+ <div className='help-text'>
+ <button
+ className='help-link'
+ onClick={this.handleGenerate}
+ >
+ {'Re-Generate'}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='Trace'
+ >
+ {'Trace: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='Trace'
+ value='true'
+ ref='Trace'
+ defaultChecked={this.props.config.SqlSettings.Trace}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='Trace'
+ value='false'
+ defaultChecked={!this.props.config.SqlSettings.Trace}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'(Development Mode) When true, executing SQL statements are written to the log.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+SqlSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/team_settings.jsx b/web/react/components/admin_console/team_settings.jsx
new file mode 100644
index 000000000..0f6f819d3
--- /dev/null
+++ b/web/react/components/admin_console/team_settings.jsx
@@ -0,0 +1,235 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+
+export default class TeamSettings extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+
+ this.state = {
+ saveNeeded: false,
+ serverError: null
+ };
+ }
+
+ handleChange() {
+ var s = {saveNeeded: true, serverError: this.state.serverError};
+ this.setState(s);
+ }
+
+ handleSubmit(e) {
+ e.preventDefault();
+ $('#save-button').button('loading');
+
+ var config = this.props.config;
+ config.TeamSettings.SiteName = React.findDOMNode(this.refs.SiteName).value.trim();
+ config.TeamSettings.RestrictCreationToDomains = React.findDOMNode(this.refs.RestrictCreationToDomains).value.trim();
+ config.TeamSettings.EnableTeamCreation = React.findDOMNode(this.refs.EnableTeamCreation).checked;
+ config.TeamSettings.EnableUserCreation = React.findDOMNode(this.refs.EnableUserCreation).checked;
+
+ var MaxUsersPerTeam = 50;
+ if (!isNaN(parseInt(React.findDOMNode(this.refs.MaxUsersPerTeam).value, 10))) {
+ MaxUsersPerTeam = parseInt(React.findDOMNode(this.refs.MaxUsersPerTeam).value, 10);
+ }
+ config.TeamSettings.MaxUsersPerTeam = MaxUsersPerTeam;
+ React.findDOMNode(this.refs.MaxUsersPerTeam).value = MaxUsersPerTeam;
+
+ Client.saveConfig(
+ config,
+ () => {
+ AsyncClient.getConfig();
+ this.setState({
+ serverError: null,
+ saveNeeded: false
+ });
+ $('#save-button').button('reset');
+ },
+ (err) => {
+ this.setState({
+ serverError: err.message,
+ saveNeeded: true
+ });
+ $('#save-button').button('reset');
+ }
+ );
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ var saveClass = 'btn';
+ if (this.state.saveNeeded) {
+ saveClass = 'btn btn-primary';
+ }
+
+ return (
+ <div className='wrapper--fixed'>
+
+ <h3>{'Team Settings'}</h3>
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='SiteName'
+ >
+ {'Site Name:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='SiteName'
+ ref='SiteName'
+ placeholder='Ex "Mattermost"'
+ defaultValue={this.props.config.TeamSettings.SiteName}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Name of service shown in login screens and UI.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='MaxUsersPerTeam'
+ >
+ {'Max Users Per Team:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='MaxUsersPerTeam'
+ ref='MaxUsersPerTeam'
+ placeholder='Ex "25"'
+ defaultValue={this.props.config.TeamSettings.MaxUsersPerTeam}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Maximum total number of users per team, including both active and inactive users.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnableTeamCreation'
+ >
+ {'Enable Team Creation: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableTeamCreation'
+ value='true'
+ ref='EnableTeamCreation'
+ defaultChecked={this.props.config.TeamSettings.EnableTeamCreation}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableTeamCreation'
+ value='false'
+ defaultChecked={!this.props.config.TeamSettings.EnableTeamCreation}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When false, the ability to create teams is disabled. The create team button displays error when pressed.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='EnableUserCreation'
+ >
+ {'Enable User Creation: '}
+ </label>
+ <div className='col-sm-8'>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableUserCreation'
+ value='true'
+ ref='EnableUserCreation'
+ defaultChecked={this.props.config.TeamSettings.EnableUserCreation}
+ onChange={this.handleChange}
+ />
+ {'true'}
+ </label>
+ <label className='radio-inline'>
+ <input
+ type='radio'
+ name='EnableUserCreation'
+ value='false'
+ defaultChecked={!this.props.config.TeamSettings.EnableUserCreation}
+ onChange={this.handleChange}
+ />
+ {'false'}
+ </label>
+ <p className='help-text'>{'When false, the ability to create accounts is disabled. The create account button displays error when pressed.'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <label
+ className='control-label col-sm-4'
+ htmlFor='RestrictCreationToDomains'
+ >
+ {'Restrict Creation To Domains:'}
+ </label>
+ <div className='col-sm-8'>
+ <input
+ type='text'
+ className='form-control'
+ id='RestrictCreationToDomains'
+ ref='RestrictCreationToDomains'
+ placeholder='Ex "corp.mattermost.com, mattermost.org"'
+ defaultValue={this.props.config.TeamSettings.RestrictCreationToDomains}
+ onChange={this.handleChange}
+ />
+ <p className='help-text'>{'Teams can only be created from a specific domain (e.g. "mattermost.org") or list of comma-separated domains (e.g. "corp.mattermost.com, mattermost.org").'}</p>
+ </div>
+ </div>
+
+ <div className='form-group'>
+ <div className='col-sm-12'>
+ {serverError}
+ <button
+ disabled={!this.state.saveNeeded}
+ type='submit'
+ className={saveClass}
+ onClick={this.handleSubmit}
+ id='save-button'
+ data-loading-text={'<span class=\'glyphicon glyphicon-refresh glyphicon-refresh-animate\'></span> Saving Config...'}
+ >
+ {'Save'}
+ </button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+ );
+ }
+}
+
+TeamSettings.propTypes = {
+ config: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/team_users.jsx b/web/react/components/admin_console/team_users.jsx
new file mode 100644
index 000000000..0a971ff15
--- /dev/null
+++ b/web/react/components/admin_console/team_users.jsx
@@ -0,0 +1,178 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var LoadingScreen = require('../loading_screen.jsx');
+var UserItem = require('./user_item.jsx');
+var ResetPasswordModal = require('./reset_password_modal.jsx');
+
+export default class UserList extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.getTeamProfiles = this.getTeamProfiles.bind(this);
+ this.getCurrentTeamProfiles = this.getCurrentTeamProfiles.bind(this);
+ this.doPasswordReset = this.doPasswordReset.bind(this);
+ this.doPasswordResetDismiss = this.doPasswordResetDismiss.bind(this);
+ this.doPasswordResetSubmit = this.doPasswordResetSubmit.bind(this);
+
+ this.state = {
+ teamId: props.team.id,
+ users: null,
+ serverError: null,
+ showPasswordModal: false,
+ user: null
+ };
+ }
+
+ componentDidMount() {
+ this.getCurrentTeamProfiles();
+ }
+
+ getCurrentTeamProfiles() {
+ this.getTeamProfiles(this.props.team.id);
+ }
+
+ // this.setState({
+ // teamId: this.state.teamId,
+ // users: this.state.users,
+ // serverError: this.state.serverError,
+ // showPasswordModal: this.state.showPasswordModal,
+ // user: this.state.user
+ // });
+
+ getTeamProfiles(teamId) {
+ Client.getProfilesForTeam(
+ teamId,
+ (users) => {
+ var memberList = [];
+ for (var id in users) {
+ if (users.hasOwnProperty(id)) {
+ memberList.push(users[id]);
+ }
+ }
+
+ memberList.sort((a, b) => {
+ if (a.username < b.username) {
+ return -1;
+ }
+
+ if (a.username > b.username) {
+ return 1;
+ }
+
+ return 0;
+ });
+
+ this.setState({
+ teamId: this.state.teamId,
+ users: memberList,
+ serverError: this.state.serverError,
+ showPasswordModal: this.state.showPasswordModal,
+ user: this.state.user
+ });
+ },
+ (err) => {
+ this.setState({
+ teamId: this.state.teamId,
+ users: null,
+ serverError: err.message,
+ showPasswordModal: this.state.showPasswordModal,
+ user: this.state.user
+ });
+ }
+ );
+ }
+
+ doPasswordReset(user) {
+ this.setState({
+ teamId: this.state.teamId,
+ users: this.state.users,
+ serverError: this.state.serverError,
+ showPasswordModal: true,
+ user
+ });
+ }
+
+ doPasswordResetDismiss() {
+ this.state.showPasswordModal = false;
+ this.state.user = null;
+ this.setState({
+ teamId: this.state.teamId,
+ users: this.state.users,
+ serverError: this.state.serverError,
+ showPasswordModal: false,
+ user: null
+ });
+ }
+
+ doPasswordResetSubmit() {
+ this.setState({
+ teamId: this.state.teamId,
+ users: this.state.users,
+ serverError: this.state.serverError,
+ showPasswordModal: false,
+ user: null
+ });
+ }
+
+ componentWillReceiveProps(newProps) {
+ this.getTeamProfiles(newProps.team.id);
+ }
+
+ componentWillUnmount() {
+ }
+
+ render() {
+ var serverError = '';
+ if (this.state.serverError) {
+ serverError = <div className='form-group has-error'><label className='control-label'>{this.state.serverError}</label></div>;
+ }
+
+ if (this.state.users == null) {
+ return (
+ <div className='wrapper--fixed'>
+ <h3>{'Users for ' + this.props.team.name}</h3>
+ {serverError}
+ <LoadingScreen />
+ </div>
+ );
+ }
+
+ var memberList = this.state.users.map((user) => {
+ return (
+ <UserItem
+ key={'user_' + user.id}
+ user={user}
+ refreshProfiles={this.getCurrentTeamProfiles}
+ doPasswordReset={this.doPasswordReset}
+ />);
+ });
+
+ return (
+ <div className='wrapper--fixed'>
+ <h3>{'Users for ' + this.props.team.name + ' (' + this.state.users.length + ')'}</h3>
+ {serverError}
+ <form
+ className='form-horizontal'
+ role='form'
+ >
+ <div className='member-list-holder'>
+ {memberList}
+ </div>
+ </form>
+ <ResetPasswordModal
+ user={this.state.user}
+ show={this.state.showPasswordModal}
+ team={this.props.team}
+ onModalSubmit={this.doPasswordResetSubmit}
+ onModalDismissed={this.doPasswordResetDismiss}
+ />
+ </div>
+ );
+ }
+}
+
+UserList.propTypes = {
+ team: React.PropTypes.object
+};
diff --git a/web/react/components/admin_console/user_item.jsx b/web/react/components/admin_console/user_item.jsx
new file mode 100644
index 000000000..32812e875
--- /dev/null
+++ b/web/react/components/admin_console/user_item.jsx
@@ -0,0 +1,266 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var Utils = require('../../utils/utils.jsx');
+
+export default class UserItem extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.handleMakeMember = this.handleMakeMember.bind(this);
+ this.handleMakeActive = this.handleMakeActive.bind(this);
+ this.handleMakeNotActive = this.handleMakeNotActive.bind(this);
+ this.handleMakeAdmin = this.handleMakeAdmin.bind(this);
+ this.handleMakeSystemAdmin = this.handleMakeSystemAdmin.bind(this);
+ this.handleResetPassword = this.handleResetPassword.bind(this);
+
+ this.state = {};
+ }
+
+ handleMakeMember(e) {
+ e.preventDefault();
+ const data = {
+ user_id: this.props.user.id,
+ new_roles: ''
+ };
+
+ Client.updateRoles(data,
+ () => {
+ this.props.refreshProfiles();
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ handleMakeActive(e) {
+ e.preventDefault();
+ Client.updateActive(this.props.user.id, true,
+ () => {
+ this.props.refreshProfiles();
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ handleMakeNotActive(e) {
+ e.preventDefault();
+ Client.updateActive(this.props.user.id, false,
+ () => {
+ this.props.refreshProfiles();
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ handleMakeAdmin(e) {
+ e.preventDefault();
+ const data = {
+ user_id: this.props.user.id,
+ new_roles: 'admin'
+ };
+
+ Client.updateRoles(data,
+ () => {
+ this.props.refreshProfiles();
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ handleMakeSystemAdmin(e) {
+ e.preventDefault();
+ const data = {
+ user_id: this.props.user.id,
+ new_roles: 'system_admin'
+ };
+
+ Client.updateRoles(data,
+ () => {
+ this.props.refreshProfiles();
+ },
+ (err) => {
+ this.setState({serverError: err.message});
+ }
+ );
+ }
+
+ handleResetPassword(e) {
+ e.preventDefault();
+ this.props.doPasswordReset(this.props.user);
+ }
+
+ render() {
+ let serverError = null;
+ if (this.state.serverError) {
+ serverError = (
+ <div className='has-error'>
+ <label className='has-error control-label'>{this.state.serverError}</label>
+ </div>
+ );
+ }
+
+ const user = this.props.user;
+ let currentRoles = 'Member';
+ if (user.roles.length > 0) {
+ if (user.roles.indexOf('system_admin') > -1) {
+ currentRoles = 'System Admin';
+ } else {
+ currentRoles = user.roles.charAt(0).toUpperCase() + user.roles.slice(1);
+ }
+ }
+
+ const email = user.email;
+ let showMakeMember = user.roles === 'admin' || user.roles === 'system_admin';
+ let showMakeAdmin = user.roles === '' || user.roles === 'system_admin';
+ let showMakeSystemAdmin = user.roles === '' || user.roles === 'admin';
+ let showMakeActive = false;
+ let showMakeNotActive = user.roles !== 'system_admin';
+
+ if (user.delete_at > 0) {
+ currentRoles = 'Inactive';
+ currentRoles = 'Inactive';
+ showMakeMember = false;
+ showMakeAdmin = false;
+ showMakeSystemAdmin = false;
+ showMakeActive = true;
+ showMakeNotActive = false;
+ }
+
+ let makeSystemAdmin = null;
+ if (showMakeSystemAdmin) {
+ makeSystemAdmin = (
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleMakeSystemAdmin}
+ >
+ {'Make System Admin'}
+ </a>
+ </li>
+ );
+ }
+
+ let makeAdmin = null;
+ if (showMakeAdmin) {
+ makeAdmin = (
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleMakeAdmin}
+ >
+ {'Make Admin'}
+ </a>
+ </li>
+ );
+ }
+
+ let makeMember = null;
+ if (showMakeMember) {
+ makeMember = (
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleMakeMember}
+ >
+ {'Make Member'}
+ </a>
+ </li>
+ );
+ }
+
+ let makeActive = null;
+ if (showMakeActive) {
+ makeActive = (
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleMakeActive}
+ >
+ {'Make Active'}
+ </a>
+ </li>
+ );
+ }
+
+ let makeNotActive = null;
+ if (showMakeNotActive) {
+ makeNotActive = (
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleMakeNotActive}
+ >
+ {'Make Inactive'}
+ </a>
+ </li>
+ );
+ }
+
+ return (
+ <div className='row member-div'>
+ <img
+ className='post-profile-img pull-left'
+ src={`/api/v1/users/${user.id}/image?time=${user.update_at}`}
+ height='36'
+ width='36'
+ />
+ <span className='member-name'>{Utils.getDisplayName(user)}</span>
+ <span className='member-email'>{email}</span>
+ <div className='dropdown member-drop'>
+ <a
+ href='#'
+ className='dropdown-toggle theme'
+ type='button'
+ id='channel_header_dropdown'
+ data-toggle='dropdown'
+ aria-expanded='true'
+ >
+ <span>{currentRoles} </span>
+ <span className='caret'></span>
+ </a>
+ <ul
+ className='dropdown-menu member-menu'
+ role='menu'
+ aria-labelledby='channel_header_dropdown'
+ >
+ {makeAdmin}
+ {makeMember}
+ {makeActive}
+ {makeNotActive}
+ {makeSystemAdmin}
+ <li role='presentation'>
+ <a
+ role='menuitem'
+ href='#'
+ onClick={this.handleResetPassword}
+ >
+ {'Reset Password'}
+ </a>
+ </li>
+ </ul>
+ </div>
+ {serverError}
+ </div>
+ );
+ }
+}
+
+UserItem.propTypes = {
+ user: React.PropTypes.object.isRequired,
+ refreshProfiles: React.PropTypes.func.isRequired,
+ doPasswordReset: React.PropTypes.func.isRequired
+};
diff --git a/web/react/components/channel_header.jsx b/web/react/components/channel_header.jsx
index 8d23ec646..b81936b57 100644
--- a/web/react/components/channel_header.jsx
+++ b/web/react/components/channel_header.jsx
@@ -55,7 +55,7 @@ export default class ChannelHeader extends React.Component {
if (!Utils.areStatesEqual(newState, this.state)) {
this.setState(newState);
}
- $('.channel-header__info .description').popover({placement: 'bottom', trigger: 'hover click', html: true, delay: {show: 500, hide: 500}});
+ $('.channel-header__info .description').popover({placement: 'bottom', trigger: 'hover', html: true, delay: {show: 500, hide: 500}});
}
onSocketChange(msg) {
if (msg.action === 'new_user') {
diff --git a/web/react/components/channel_loader.jsx b/web/react/components/channel_loader.jsx
index ce6f60f87..39c86405c 100644
--- a/web/react/components/channel_loader.jsx
+++ b/web/react/components/channel_loader.jsx
@@ -12,6 +12,7 @@ var PostStore = require('../stores/post_store.jsx');
var UserStore = require('../stores/user_store.jsx');
var Utils = require('../utils/utils.jsx');
+var Constants = require('../utils/constants.jsx');
export default class ChannelLoader extends React.Component {
constructor(props) {
@@ -68,33 +69,19 @@ export default class ChannelLoader extends React.Component {
/* Update CSS classes to match user theme */
var user = UserStore.getCurrentUser();
- if (user.props && user.props.theme) {
- Utils.changeCss('div.theme', 'background-color:' + user.props.theme + ';');
- Utils.changeCss('.btn.btn-primary', 'background: ' + user.props.theme + ';');
- Utils.changeCss('.modal .modal-header', 'background: ' + user.props.theme + ';');
- Utils.changeCss('.mention', 'background: ' + user.props.theme + ';');
- Utils.changeCss('.mention-link', 'color: ' + user.props.theme + ';');
- Utils.changeCss('@media(max-width: 768px){.search-bar__container', 'background: ' + user.props.theme + ';}');
- Utils.changeCss('.search-item-container:hover', 'background: ' + Utils.changeOpacity(user.props.theme, 0.05) + ';');
- }
-
- if (user.props.theme !== '#000000' && user.props.theme !== '#585858') {
- Utils.changeCss('.btn.btn-primary:hover, .btn.btn-primary:active, .btn.btn-primary:focus', 'background: ' + Utils.changeColor(user.props.theme, -10) + ';');
- Utils.changeCss('a.theme', 'color:' + user.props.theme + '; fill:' + user.props.theme + '!important;');
- } else if (user.props.theme === '#000000') {
- Utils.changeCss('.btn.btn-primary:hover, .btn.btn-primary:active, .btn.btn-primary:focus', 'background: ' + Utils.changeColor(user.props.theme, +50) + ';');
- $('.team__header').addClass('theme--black');
- } else if (user.props.theme === '#585858') {
- Utils.changeCss('.btn.btn-primary:hover, .btn.btn-primary:active, .btn.btn-primary:focus', 'background: ' + Utils.changeColor(user.props.theme, +10) + ';');
- $('.team__header').addClass('theme--gray');
+ if ($.isPlainObject(user.theme_props) && !$.isEmptyObject(user.theme_props)) {
+ Utils.applyTheme(user.theme_props);
+ } else {
+ Utils.applyTheme(Constants.THEMES.default);
}
/* Setup global mouse events */
- $('body').on('click.userpopover', function popOver(e) {
- if ($(e.target).attr('data-toggle') !== 'popover' &&
- $(e.target).parents('.popover.in').length === 0) {
- $('.user-popover').popover('hide');
- }
+ $('body').on('click', function hidePopover(e) {
+ $('[data-toggle="popover"]').each(function eachPopover() {
+ if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
+ $(this).popover('hide');
+ }
+ });
});
$('body').on('mouseenter mouseleave', '.post', function mouseOver(ev) {
@@ -122,6 +109,13 @@ export default class ChannelLoader extends React.Component {
$('.modal-body').css('overflow-y', 'auto');
$('.modal-body').css('max-height', $(window).height() * 0.7);
});
+
+ /* Prevent backspace from navigating back a page */
+ $(window).on('keydown.preventBackspace', (e) => {
+ if (e.which === 8 && !$(e.target).is('input, textarea')) {
+ e.preventDefault();
+ }
+ });
}
componentWillUnmount() {
clearInterval(this.intervalId);
@@ -136,6 +130,8 @@ export default class ChannelLoader extends React.Component {
$('body').off('mouseenter mouseleave', '.post.post--comment.same--root');
$('.modal').off('show.bs.modal');
+
+ $(window).off('keydown.preventBackspace');
}
onSocketChange(msg) {
if (msg && msg.user_id && msg.user_id !== UserStore.getCurrentId()) {
diff --git a/web/react/components/channel_notifications.jsx b/web/react/components/channel_notifications.jsx
index 83067240d..9eda68b38 100644
--- a/web/react/components/channel_notifications.jsx
+++ b/web/react/components/channel_notifications.jsx
@@ -163,10 +163,22 @@ export default class ChannelNotifications extends React.Component {
}.bind(this);
let curChannel = ChannelStore.get(this.state.channelId);
- let extraInfo = (<span>These settings will override the global notification settings</span>);
+ let extraInfo = (
+ <span>
+ These settings will override the global notification settings.
+ <br/>
+ Desktop notifications are available on Firefox, Safari, and Chrome.
+ </span>
+ );
if (curChannel && curChannel.display_name) {
- extraInfo = (<span>These settings will override the global notification settings for the <b>{curChannel.display_name}</b> channel</span>);
+ extraInfo = (
+ <span>
+ These settings will override the global notification settings for the <b>{curChannel.display_name}</b> channel.
+ <br/>
+ Desktop notifications are available on Firefox, Safari, and Chrome.
+ </span>
+ );
}
return (
diff --git a/web/react/components/create_comment.jsx b/web/react/components/create_comment.jsx
index c2fc0dcf3..5097b3aa5 100644
--- a/web/react/components/create_comment.jsx
+++ b/web/react/components/create_comment.jsx
@@ -28,6 +28,7 @@ export default class CreateComment extends React.Component {
this.handleUploadStart = this.handleUploadStart.bind(this);
this.handleFileUploadComplete = this.handleFileUploadComplete.bind(this);
this.handleUploadError = this.handleUploadError.bind(this);
+ this.handleTextDrop = this.handleTextDrop.bind(this);
this.removePreview = this.removePreview.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.getFileCount = this.getFileCount.bind(this);
@@ -42,6 +43,12 @@ export default class CreateComment extends React.Component {
submitting: false
};
}
+ componentDidUpdate(prevProps, prevState) {
+ if (prevState.uploadsInProgress < this.state.uploadsInProgress) {
+ $('.post-right__scroll').scrollTop($('.post-right__scroll')[0].scrollHeight);
+ $('.post-right__scroll').perfectScrollbar('update');
+ }
+ }
handleSubmit(e) {
e.preventDefault();
@@ -178,6 +185,11 @@ export default class CreateComment extends React.Component {
this.setState({serverError: err});
}
}
+ handleTextDrop(text) {
+ const newText = this.state.messageText + text;
+ this.handleUserInput(newText);
+ Utils.setCaretPosition(React.findDOMNode(this.refs.textbox.refs.message), newText.length);
+ }
removePreview(id) {
let previews = this.state.previews;
let uploadsInProgress = this.state.uploadsInProgress;
@@ -264,6 +276,7 @@ export default class CreateComment extends React.Component {
onUploadStart={this.handleUploadStart}
onFileUpload={this.handleFileUploadComplete}
onUploadError={this.handleUploadError}
+ onTextDrop={this.handleTextDrop}
postType='comment'
channelId={this.props.channelId}
/>
diff --git a/web/react/components/create_post.jsx b/web/react/components/create_post.jsx
index d9e67836d..0cd14747d 100644
--- a/web/react/components/create_post.jsx
+++ b/web/react/components/create_post.jsx
@@ -23,6 +23,7 @@ export default class CreatePost extends React.Component {
this.lastTime = 0;
+ this.getCurrentDraft = this.getCurrentDraft.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.postMsgKeyPress = this.postMsgKeyPress.bind(this);
this.handleUserInput = this.handleUserInput.bind(this);
@@ -30,35 +31,52 @@ export default class CreatePost extends React.Component {
this.handleUploadStart = this.handleUploadStart.bind(this);
this.handleFileUploadComplete = this.handleFileUploadComplete.bind(this);
this.handleUploadError = this.handleUploadError.bind(this);
+ this.handleTextDrop = this.handleTextDrop.bind(this);
this.removePreview = this.removePreview.bind(this);
this.onChange = this.onChange.bind(this);
this.getFileCount = this.getFileCount.bind(this);
PostStore.clearDraftUploads();
- const draft = PostStore.getCurrentDraft();
- let previews = [];
- let messageText = '';
- let uploadsInProgress = [];
- if (draft && draft.previews && draft.message) {
- previews = draft.previews;
- messageText = draft.message;
- uploadsInProgress = draft.uploadsInProgress;
- }
+ const draft = this.getCurrentDraft();
this.state = {
channelId: ChannelStore.getCurrentId(),
- messageText: messageText,
- uploadsInProgress: uploadsInProgress,
- previews: previews,
+ messageText: draft.messageText,
+ uploadsInProgress: draft.uploadsInProgress,
+ previews: draft.previews,
submitting: false,
- initialText: messageText
+ initialText: draft.messageText
};
}
componentDidUpdate(prevProps, prevState) {
if (prevState.previews.length !== this.state.previews.length) {
this.resizePostHolder();
+ return;
+ }
+
+ if (prevState.uploadsInProgress !== this.state.uploadsInProgress) {
+ this.resizePostHolder();
+ return;
+ }
+ }
+ getCurrentDraft() {
+ const draft = PostStore.getCurrentDraft();
+ const safeDraft = {previews: [], messageText: '', uploadsInProgress: []};
+
+ if (draft) {
+ if (draft.message) {
+ safeDraft.messageText = draft.message;
+ }
+ if (draft.previews) {
+ safeDraft.previews = draft.previews;
+ }
+ if (draft.uploadsInProgress) {
+ safeDraft.uploadsInProgress = draft.uploadsInProgress;
+ }
}
+
+ return safeDraft;
}
handleSubmit(e) {
e.preventDefault();
@@ -67,7 +85,7 @@ export default class CreatePost extends React.Component {
return;
}
- let post = {};
+ const post = {};
post.filenames = [];
post.message = this.state.messageText;
@@ -87,20 +105,20 @@ export default class CreatePost extends React.Component {
this.state.channelId,
post.message,
false,
- function handleCommandSuccess(data) {
+ (data) => {
PostStore.storeDraft(data.channel_id, null);
this.setState({messageText: '', submitting: false, postError: null, previews: [], serverError: null});
if (data.goto_location.length > 0) {
window.location.href = data.goto_location;
}
- }.bind(this),
- function handleCommandError(err) {
- let state = {};
+ },
+ (err) => {
+ const state = {};
state.serverError = err.message;
state.submitting = false;
this.setState(state);
- }.bind(this)
+ }
);
} else {
post.channel_id = this.state.channelId;
@@ -121,10 +139,10 @@ export default class CreatePost extends React.Component {
this.setState({messageText: '', submitting: false, postError: null, previews: [], serverError: null});
Client.createPost(post, channel,
- function handlePostSuccess(data) {
+ (data) => {
AsyncClient.getPosts();
- let member = ChannelStore.getMember(channel.id);
+ const member = ChannelStore.getMember(channel.id);
member.msg_count = channel.total_msg_count;
member.last_viewed_at = Date.now();
ChannelStore.setChannelMember(member);
@@ -134,8 +152,8 @@ export default class CreatePost extends React.Component {
post: data
});
},
- function handlePostError(err) {
- let state = {};
+ (err) => {
+ const state = {};
if (err.message === 'Invalid RootId parameter') {
if ($('#post_deleted').length > 0) {
@@ -149,7 +167,7 @@ export default class CreatePost extends React.Component {
state.submitting = false;
this.setState(state);
- }.bind(this)
+ }
);
}
}
@@ -167,9 +185,9 @@ export default class CreatePost extends React.Component {
}
}
handleUserInput(messageText) {
- this.setState({messageText: messageText});
+ this.setState({messageText});
- let draft = PostStore.getCurrentDraft();
+ const draft = PostStore.getCurrentDraft();
draft.message = messageText;
PostStore.storeCurrentDraft(draft);
}
@@ -179,7 +197,7 @@ export default class CreatePost extends React.Component {
$(window).trigger('resize');
}
handleUploadStart(clientIds, channelId) {
- let draft = PostStore.getDraft(channelId);
+ const draft = PostStore.getDraft(channelId);
draft.uploadsInProgress = draft.uploadsInProgress.concat(clientIds);
PostStore.storeDraft(channelId, draft);
@@ -187,7 +205,7 @@ export default class CreatePost extends React.Component {
this.setState({uploadsInProgress: draft.uploadsInProgress});
}
handleFileUploadComplete(filenames, clientIds, channelId) {
- let draft = PostStore.getDraft(channelId);
+ const draft = PostStore.getDraft(channelId);
// remove each finished file from uploads
for (let i = 0; i < clientIds.length; i++) {
@@ -205,7 +223,7 @@ export default class CreatePost extends React.Component {
}
handleUploadError(err, clientId) {
if (clientId !== -1) {
- let draft = PostStore.getDraft(this.state.channelId);
+ const draft = PostStore.getDraft(this.state.channelId);
const index = draft.uploadsInProgress.indexOf(clientId);
if (index !== -1) {
@@ -219,9 +237,14 @@ export default class CreatePost extends React.Component {
this.setState({serverError: err});
}
}
+ handleTextDrop(text) {
+ const newText = this.state.messageText + text;
+ this.handleUserInput(newText);
+ Utils.setCaretPosition(React.findDOMNode(this.refs.textbox.refs.message), newText.length);
+ }
removePreview(id) {
- let previews = this.state.previews;
- let uploadsInProgress = this.state.uploadsInProgress;
+ const previews = Object.assign([], this.state.previews);
+ const uploadsInProgress = this.state.uploadsInProgress;
// id can either be the path of an uploaded file or the client id of an in progress upload
let index = previews.indexOf(id);
@@ -236,12 +259,12 @@ export default class CreatePost extends React.Component {
}
}
- let draft = PostStore.getCurrentDraft();
+ const draft = PostStore.getCurrentDraft();
draft.previews = previews;
draft.uploadsInProgress = uploadsInProgress;
PostStore.storeCurrentDraft(draft);
- this.setState({previews: previews, uploadsInProgress: uploadsInProgress});
+ this.setState({previews, uploadsInProgress});
}
componentDidMount() {
ChannelStore.addChangeListener(this.onChange);
@@ -253,18 +276,9 @@ export default class CreatePost extends React.Component {
onChange() {
const channelId = ChannelStore.getCurrentId();
if (this.state.channelId !== channelId) {
- let draft = PostStore.getCurrentDraft();
-
- let previews = [];
- let messageText = '';
- let uploadsInProgress = [];
- if (draft && draft.previews && draft.message) {
- previews = draft.previews;
- messageText = draft.message;
- uploadsInProgress = draft.uploadsInProgress;
- }
+ const draft = this.getCurrentDraft();
- this.setState({channelId: channelId, messageText: messageText, initialText: messageText, submitting: false, serverError: null, postError: null, previews: previews, uploadsInProgress: uploadsInProgress});
+ this.setState({channelId, messageText: draft.messageText, initialText: draft.messageText, submitting: false, serverError: null, postError: null, previews: draft.previews, uploadsInProgress: draft.uploadsInProgress});
}
}
getFileCount(channelId) {
@@ -332,6 +346,7 @@ export default class CreatePost extends React.Component {
onUploadStart={this.handleUploadStart}
onFileUpload={this.handleFileUploadComplete}
onUploadError={this.handleUploadError}
+ onTextDrop={this.handleTextDrop}
postType='post'
channelId=''
/>
diff --git a/web/react/components/delete_channel_modal.jsx b/web/react/components/delete_channel_modal.jsx
index 4efb9cb23..44c54db72 100644
--- a/web/react/components/delete_channel_modal.jsx
+++ b/web/react/components/delete_channel_modal.jsx
@@ -4,6 +4,7 @@
const Client = require('../utils/client.jsx');
const AsyncClient = require('../utils/async_client.jsx');
const ChannelStore = require('../stores/channel_store.jsx');
+var TeamStore = require('../stores/team_store.jsx');
export default class DeleteChannelModal extends React.Component {
constructor(props) {
@@ -24,7 +25,7 @@ export default class DeleteChannelModal extends React.Component {
Client.deleteChannel(this.state.channelId,
function handleDeleteSuccess() {
AsyncClient.getChannels(true);
- window.location.href = '/';
+ window.location.href = TeamStore.getCurrentTeamUrl() + '/channels/town-square';
},
function handleDeleteError(err) {
AsyncClient.dispatchError(err, 'handleDelete');
diff --git a/web/react/components/email_verify.jsx b/web/react/components/email_verify.jsx
index 92123956f..8d3f15525 100644
--- a/web/react/components/email_verify.jsx
+++ b/web/react/components/email_verify.jsx
@@ -10,12 +10,14 @@ export default class EmailVerify extends React.Component {
this.state = {};
}
handleResend() {
- window.location.href = window.location.href + '&resend=true';
+ const newAddress = window.location.href.replace('&resend_success=true', '');
+ window.location.href = newAddress + '&resend=true';
}
render() {
var title = '';
var body = '';
var resend = '';
+ var resendConfirm = '';
if (this.props.isVerified === 'true') {
title = global.window.config.SiteName + ' Email Verified';
body = <p>Your email has been verified! Click <a href={this.props.teamURL + '?email=' + this.props.userEmail}>here</a> to log in.</p>;
@@ -30,6 +32,9 @@ export default class EmailVerify extends React.Component {
Resend Email
</button>
);
+ if (this.props.resendSuccess) {
+ resendConfirm = <div><br /><p className='alert alert-success'><i className='fa fa-check'></i>{' Verification email sent.'}</p></div>;
+ }
}
return (
@@ -41,6 +46,7 @@ export default class EmailVerify extends React.Component {
<div className='panel-body'>
{body}
{resend}
+ {resendConfirm}
</div>
</div>
</div>
@@ -51,10 +57,12 @@ export default class EmailVerify extends React.Component {
EmailVerify.defaultProps = {
isVerified: 'false',
teamURL: '',
- userEmail: ''
+ userEmail: '',
+ resendSuccess: 'false'
};
EmailVerify.propTypes = {
isVerified: React.PropTypes.string,
teamURL: React.PropTypes.string,
- userEmail: React.PropTypes.string
+ userEmail: React.PropTypes.string,
+ resendSuccess: React.PropTypes.string
};
diff --git a/web/react/components/error_bar.jsx b/web/react/components/error_bar.jsx
index 87d94a41d..05726e860 100644
--- a/web/react/components/error_bar.jsx
+++ b/web/react/components/error_bar.jsx
@@ -2,10 +2,6 @@
// See License.txt for license information.
var ErrorStore = require('../stores/error_store.jsx');
-var utils = require('../utils/utils.jsx');
-var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
-var Constants = require('../utils/constants.jsx');
-var ActionTypes = Constants.ActionTypes;
export default class ErrorBar extends React.Component {
constructor() {
@@ -13,70 +9,79 @@ export default class ErrorBar extends React.Component {
this.onErrorChange = this.onErrorChange.bind(this);
this.handleClose = this.handleClose.bind(this);
+ this.prevTimer = null;
- this.state = this.getStateFromStores();
- if (this.state.message) {
- setTimeout(this.handleClose, 10000);
+ this.state = ErrorStore.getLastError();
+ if (this.state && this.state.message) {
+ this.prevTimer = setTimeout(this.handleClose, 10000);
}
}
- getStateFromStores() {
- var error = ErrorStore.getLastError();
- if (!error || error.message === 'There appears to be a problem with your internet connection') {
- return {message: null};
- }
- return {message: error.message};
- }
componentDidMount() {
ErrorStore.addChangeListener(this.onErrorChange);
$('body').css('padding-top', $(React.findDOMNode(this)).outerHeight());
- $(window).resize(function onResize() {
- if (this.state.message) {
+ $(window).resize(() => {
+ if (this.state && this.state.message) {
$('body').css('padding-top', $(React.findDOMNode(this)).outerHeight());
}
- }.bind(this));
+ });
}
+
componentWillUnmount() {
ErrorStore.removeChangeListener(this.onErrorChange);
}
+
onErrorChange() {
- var newState = this.getStateFromStores();
- if (!utils.areStatesEqual(newState, this.state)) {
- if (newState.message) {
- setTimeout(this.handleClose, 10000);
- }
+ var newState = ErrorStore.getLastError();
+
+ if (this.prevTimer != null) {
+ clearInterval(this.prevTimer);
+ this.prevTimer = null;
+ }
+ if (newState) {
this.setState(newState);
+ this.prevTimer = setTimeout(this.handleClose, 10000);
+ } else {
+ this.setState({message: null});
}
}
+
handleClose(e) {
if (e) {
e.preventDefault();
}
- AppDispatcher.handleServerAction({
- type: ActionTypes.RECIEVED_ERROR,
- err: null
- });
+ ErrorStore.storeLastError(null);
+ ErrorStore.emitChange();
$('body').css('padding-top', '0');
}
+
render() {
- if (this.state.message) {
- return (
- <div className='error-bar'>
- <span>{this.state.message}</span>
- <a
- href='#'
- className='error-bar__close'
- onClick={this.handleClose}
- >
- &times;
- </a>
- </div>
- );
+ if (!this.state) {
+ return <div/>;
+ }
+
+ if (!this.state.message) {
+ return <div/>;
+ }
+
+ if (this.state.connErrorCount < 7) {
+ return <div/>;
}
- return <div/>;
+ return (
+ <div className='error-bar'>
+ <span>{this.state.message}</span>
+ <a
+ href='#'
+ className='error-bar__close'
+ onClick={this.handleClose}
+ >
+ &times;
+ </a>
+ </div>
+ );
}
}
diff --git a/web/react/components/file_attachment.jsx b/web/react/components/file_attachment.jsx
index c9aa06a97..888f24aa5 100644
--- a/web/react/components/file_attachment.jsx
+++ b/web/react/components/file_attachment.jsx
@@ -143,10 +143,7 @@ export default class FileAttachment extends React.Component {
>
<a className='post-image__thumbnail'
href='#'
- onClick={this.props.handleImageClick}
- data-img-id={this.props.index}
- data-toggle='modal'
- data-target={'#' + this.props.modalId}
+ onClick={() => this.props.handleImageClick(this.props.index)}
>
{thumbnail}
</a>
@@ -187,9 +184,6 @@ FileAttachment.propTypes = {
// the index of this attachment preview in the parent FileAttachmentList
index: React.PropTypes.number.isRequired,
- // the identifier of the modal dialog used to preview files
- modalId: React.PropTypes.string.isRequired,
-
- // handler for when the thumbnail is clicked
+ // handler for when the thumbnail is clicked passed the index above
handleImageClick: React.PropTypes.func
};
diff --git a/web/react/components/file_attachment_list.jsx b/web/react/components/file_attachment_list.jsx
index abe72089a..212d4a958 100644
--- a/web/react/components/file_attachment_list.jsx
+++ b/web/react/components/file_attachment_list.jsx
@@ -11,23 +11,21 @@ export default class FileAttachmentList extends React.Component {
this.handleImageClick = this.handleImageClick.bind(this);
- this.state = {startImgId: 0};
+ this.state = {showPreviewModal: false, startImgId: 0};
}
- handleImageClick(e) {
- this.setState({startImgId: parseInt($(e.target.parentNode).attr('data-img-id'), 10)});
+ handleImageClick(indexClicked) {
+ this.setState({showPreviewModal: true, startImgId: indexClicked});
}
render() {
var filenames = this.props.filenames;
- var modalId = this.props.modalId;
var postFiles = [];
for (var i = 0; i < filenames.length && i < Constants.MAX_DISPLAY_FILES; i++) {
postFiles.push(
<FileAttachment
- key={i}
+ key={'file_attachment_' + i}
filename={filenames[i]}
index={i}
- modalId={modalId}
handleImageClick={this.handleImageClick}
/>
);
@@ -39,9 +37,10 @@ export default class FileAttachmentList extends React.Component {
{postFiles}
</div>
<ViewImageModal
+ show={this.state.showPreviewModal}
+ onModalDismissed={() => this.setState({showPreviewModal: false})}
channelId={this.props.channelId}
userId={this.props.userId}
- modalId={modalId}
startId={this.state.startImgId}
filenames={filenames}
/>
@@ -55,9 +54,6 @@ FileAttachmentList.propTypes = {
// a list of file pathes displayed by this
filenames: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
- // the identifier of the modal dialog used to preview files
- modalId: React.PropTypes.string.isRequired,
-
// the channel that this is part of
channelId: React.PropTypes.string,
diff --git a/web/react/components/file_upload.jsx b/web/react/components/file_upload.jsx
index 3cb284171..3dc4e5de2 100644
--- a/web/react/components/file_upload.jsx
+++ b/web/react/components/file_upload.jsx
@@ -110,7 +110,7 @@ export default class FileUpload extends React.Component {
if (typeof files !== 'string' && files.length) {
this.uploadFiles(files);
} else {
- this.props.onUploadError('Invalid file upload', -1);
+ this.props.onTextDrop(e.originalEvent.dataTransfer.getData('Text'));
}
}
@@ -266,6 +266,7 @@ FileUpload.propTypes = {
getFileCount: React.PropTypes.func,
onFileUpload: React.PropTypes.func,
onUploadStart: React.PropTypes.func,
+ onTextDrop: React.PropTypes.func,
channelId: React.PropTypes.string,
postType: React.PropTypes.string
};
diff --git a/web/react/components/invite_member_modal.jsx b/web/react/components/invite_member_modal.jsx
index 650a72516..395b98630 100644
--- a/web/react/components/invite_member_modal.jsx
+++ b/web/react/components/invite_member_modal.jsx
@@ -21,7 +21,7 @@ export default class InviteMemberModal extends React.Component {
emailErrors: {},
firstNameErrors: {},
lastNameErrors: {},
- emailEnabled: !global.window.config.ByPassEmail
+ emailEnabled: global.window.config.SendEmailNotifications === 'true'
};
}
diff --git a/web/react/components/login.jsx b/web/react/components/login.jsx
index ffc07a4dd..8cc4f1483 100644
--- a/web/react/components/login.jsx
+++ b/web/react/components/login.jsx
@@ -5,7 +5,6 @@ const Utils = require('../utils/utils.jsx');
const Client = require('../utils/client.jsx');
const UserStore = require('../stores/user_store.jsx');
const BrowserStore = require('../stores/browser_store.jsx');
-const Constants = require('../utils/constants.jsx');
export default class Login extends React.Component {
constructor(props) {
@@ -95,10 +94,8 @@ export default class Login extends React.Component {
focusEmail = true;
}
- const authServices = JSON.parse(this.props.authServices);
-
let loginMessage = [];
- if (authServices.indexOf(Constants.GITLAB_SERVICE) !== -1) {
+ if (global.window.config.EnableSignUpWithGitLab === 'true') {
loginMessage.push(
<a
className='btn btn-custom-login gitlab'
@@ -116,7 +113,7 @@ export default class Login extends React.Component {
}
let emailSignup;
- if (authServices.indexOf(Constants.EMAIL_SERVICE) !== -1) {
+ if (global.window.config.EnableSignUpWithEmail === 'true') {
emailSignup = (
<div>
<div className={'form-group' + errorClass}>
@@ -205,11 +202,9 @@ export default class Login extends React.Component {
Login.defaultProps = {
teamName: '',
- teamDisplayName: '',
- authServices: ''
+ teamDisplayName: ''
};
Login.propTypes = {
teamName: React.PropTypes.string,
- teamDisplayName: React.PropTypes.string,
- authServices: React.PropTypes.string
+ teamDisplayName: React.PropTypes.string
};
diff --git a/web/react/components/more_direct_channels.jsx b/web/react/components/more_direct_channels.jsx
index f27b09ecc..b7bce9b34 100644
--- a/web/react/components/more_direct_channels.jsx
+++ b/web/react/components/more_direct_channels.jsx
@@ -114,7 +114,7 @@ export default class MoreDirectChannels extends React.Component {
<span aria-hidden='true'>&times;</span>
<span className='sr-only'>Close</span>
</button>
- <h4 className='modal-title'>More Private Messages</h4>
+ <h4 className='modal-title'>More Direct Messages</h4>
</div>
<div className='modal-body'>
<ul className='nav nav-pills nav-stacked'>
diff --git a/web/react/components/navbar.jsx b/web/react/components/navbar.jsx
index da9874b0b..bdb50cd9e 100644
--- a/web/react/components/navbar.jsx
+++ b/web/react/components/navbar.jsx
@@ -262,7 +262,7 @@ export default class Navbar extends React.Component {
return (
<div className='navbar-brand'>
<a
- href='/'
+ href={TeamStore.getCurrentTeamUrl() + '/channels/town-square'}
className='heading'
>
{channelTitle}
diff --git a/web/react/components/new_channel_modal.jsx b/web/react/components/new_channel_modal.jsx
index c43137744..c8ef59b4a 100644
--- a/web/react/components/new_channel_modal.jsx
+++ b/web/react/components/new_channel_modal.jsx
@@ -93,6 +93,7 @@ export default class NewChannelModal extends React.Component {
<span>
<Modal
show={this.props.show}
+ bsSize='large'
onHide={this.props.onModalDismissed}
>
<Modal.Header closeButton={true}>
@@ -122,7 +123,7 @@ export default class NewChannelModal extends React.Component {
/>
{displayNameError}
<p className='input__help dark'>
- {'Channel URL: ' + prettyTeamURL + this.props.channelData.name + ' ('}
+ {'URL: ' + prettyTeamURL + this.props.channelData.name + ' ('}
<a
href='#'
onClick={this.props.onChangeURLPressed}
diff --git a/web/react/components/password_reset_send_link.jsx b/web/react/components/password_reset_send_link.jsx
index 1e6cc3607..37d4a58cb 100644
--- a/web/react/components/password_reset_send_link.jsx
+++ b/web/react/components/password_reset_send_link.jsx
@@ -1,6 +1,7 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
+const Utils = require('../utils/utils.jsx');
var client = require('../utils/client.jsx');
export default class PasswordResetSendLink extends React.Component {
@@ -15,8 +16,8 @@ export default class PasswordResetSendLink extends React.Component {
e.preventDefault();
var state = {};
- var email = React.findDOMNode(this.refs.email).value.trim();
- if (!email) {
+ var email = React.findDOMNode(this.refs.email).value.trim().toLowerCase();
+ if (!email || !Utils.isEmail(email)) {
state.error = 'Please enter a valid email address.';
this.setState(state);
return;
@@ -67,7 +68,7 @@ export default class PasswordResetSendLink extends React.Component {
<p>{'To reset your password, enter the email address you used to sign up for ' + this.props.teamDisplayName + '.'}</p>
<div className={formClass}>
<input
- type='text'
+ type='email'
className='form-control'
name='email'
ref='email'
diff --git a/web/react/components/popover_list_members.jsx b/web/react/components/popover_list_members.jsx
index ec873dd00..a2ca8b00f 100644
--- a/web/react/components/popover_list_members.jsx
+++ b/web/react/components/popover_list_members.jsx
@@ -65,7 +65,7 @@ export default class PopoverListMembers extends React.Component {
>
{count}
<span
- className='glyphicon glyphicon-user'
+ className='fa fa-user'
aria-hidden='true'
/>
</div>
diff --git a/web/react/components/post.jsx b/web/react/components/post.jsx
index d3c6befd0..9127f00de 100644
--- a/web/react/components/post.jsx
+++ b/web/react/components/post.jsx
@@ -51,7 +51,7 @@ export default class Post extends React.Component {
var post = this.props.post;
client.createPost(post, post.channel_id,
- function success(data) {
+ (data) => {
AsyncClient.getPosts();
var channel = ChannelStore.get(post.channel_id);
@@ -65,11 +65,11 @@ export default class Post extends React.Component {
post: data
});
},
- function error() {
+ () => {
post.state = Constants.POST_FAILED;
PostStore.updatePendingPost(post);
this.forceUpdate();
- }.bind(this)
+ }
);
post.state = Constants.POST_LOADING;
@@ -81,31 +81,52 @@ export default class Post extends React.Component {
return true;
}
- return false;
- }
- render() {
- var post = this.props.post;
- var parentPost = this.props.parentPost;
- var posts = this.props.posts;
+ if (nextProps.sameRoot !== this.props.sameRoot) {
+ return true;
+ }
- var type = 'Post';
- if (post.root_id && post.root_id.length > 0) {
- type = 'Comment';
+ if (nextProps.sameUser !== this.props.sameUser) {
+ return true;
+ }
+
+ if (this.getCommentCount(nextProps) !== this.getCommentCount(this.props)) {
+ return true;
}
- var commentCount = 0;
- var commentRootId;
+ return false;
+ }
+ getCommentCount(props) {
+ const post = props.post;
+ const parentPost = props.parentPost;
+ const posts = props.posts;
+
+ let commentCount = 0;
+ let commentRootId;
if (parentPost) {
commentRootId = post.root_id;
} else {
commentRootId = post.id;
}
- for (var postId in posts) {
+ for (let postId in posts) {
if (posts[postId].root_id === commentRootId) {
commentCount += 1;
}
}
+ return commentCount;
+ }
+ render() {
+ var post = this.props.post;
+ var parentPost = this.props.parentPost;
+ var posts = this.props.posts;
+
+ var type = 'Post';
+ if (post.root_id && post.root_id.length > 0) {
+ type = 'Comment';
+ }
+
+ const commentCount = this.getCommentCount(this.props);
+
var rootUser;
if (this.props.sameRoot) {
rootUser = 'same--root';
diff --git a/web/react/components/post_body.jsx b/web/react/components/post_body.jsx
index e0682e997..6e98e4aba 100644
--- a/web/react/components/post_body.jsx
+++ b/web/react/components/post_body.jsx
@@ -35,7 +35,6 @@ export default class PostBody extends React.Component {
parseEmojis() {
twemoji.parse(React.findDOMNode(this), {size: Constants.EMOJI_SIZE});
- global.window.emojify.run(React.findDOMNode(this.refs.message_span));
}
componentDidMount() {
@@ -142,7 +141,6 @@ export default class PostBody extends React.Component {
fileAttachmentHolder = (
<FileAttachmentList
filenames={filenames}
- modalId={`view_image_modal_${post.id}`}
channelId={post.channel_id}
userId={post.user_id}
/>
diff --git a/web/react/components/post_info.jsx b/web/react/components/post_info.jsx
index d2a0a4035..824e7ef39 100644
--- a/web/react/components/post_info.jsx
+++ b/web/react/components/post_info.jsx
@@ -5,6 +5,8 @@ var UserStore = require('../stores/user_store.jsx');
var utils = require('../utils/utils.jsx');
var Constants = require('../utils/constants.jsx');
+var Tooltip = ReactBootstrap.Tooltip;
+var OverlayTrigger = ReactBootstrap.OverlayTrigger;
export default class PostInfo extends React.Component {
constructor(props) {
@@ -148,15 +150,19 @@ export default class PostInfo extends React.Component {
var dropdown = this.createDropdown();
+ let tooltip = <Tooltip>{utils.displayDate(post.create_at)} at ${utils.displayTime(post.create_at)}</Tooltip>;
+
return (
<ul className='post-header post-info'>
<li className='post-header-col'>
- <time
- className='post-profile-time'
- title={new Date(post.create_at).toString()}
+ <OverlayTrigger
+ placement='top'
+ overlay={tooltip}
>
- {utils.displayDateTime(post.create_at)}
- </time>
+ <time className='post-profile-time'>
+ {utils.displayDateTime(post.create_at)}
+ </time>
+ </OverlayTrigger>
</li>
<li className='post-header-col post-header__reply'>
<div className='dropdown'>
diff --git a/web/react/components/post_list.jsx b/web/react/components/post_list.jsx
index 703e548fb..3e1e075bb 100644
--- a/web/react/components/post_list.jsx
+++ b/web/react/components/post_list.jsx
@@ -105,18 +105,18 @@ export default class PostList extends React.Component {
UserStore.addStatusesChangeListener(this.onTimeChange);
SocketStore.addChangeListener(this.onSocketChange);
- var postHolder = $(React.findDOMNode(this.refs.postlist));
+ const postHolder = $(React.findDOMNode(this.refs.postlist));
- $(window).on('resize.' + this.props.channelId, function resize() {
+ $(window).resize(() => {
this.resize();
if (!this.scrolled) {
this.scrollToBottom();
}
- }.bind(this));
+ });
- postHolder.on('scroll', function scroll() {
- var position = postHolder.scrollTop() + postHolder.height() + 14;
- var bottom = postHolder[0].scrollHeight;
+ postHolder.on('scroll', () => {
+ const position = postHolder.scrollTop() + postHolder.height() + 14;
+ const bottom = postHolder[0].scrollHeight;
if (position >= bottom) {
this.scrolled = false;
@@ -128,7 +128,7 @@ export default class PostList extends React.Component {
this.userHasSeenNew = true;
}
this.isUserScroll = true;
- }.bind(this));
+ });
$('.post-list__content div .post').removeClass('post--last');
$('.post-list__content div:last-child .post').addClass('post--last');
@@ -146,7 +146,7 @@ export default class PostList extends React.Component {
UserStore.removeStatusesChangeListener(this.onTimeChange);
SocketStore.removeChangeListener(this.onSocketChange);
$('body').off('click.userpopover');
- $(window).off('resize.' + this.props.channelId);
+ $(window).off('resize');
var postHolder = $(React.findDOMNode(this.refs.postlist));
postHolder.off('scroll');
}
@@ -326,8 +326,8 @@ export default class PostList extends React.Component {
<strong><UserProfile userId={teammate.id} /></strong>
</div>
<p className='channel-intro-text'>
- {'This is the start of your private message history with ' + teammateName + '.'}<br/>
- {'Private messages and files shared here are not shown to people outside this area.'}
+ {'This is the start of your direct message history with ' + teammateName + '.'}<br/>
+ {'Direct messages and files shared here are not shown to people outside this area.'}
</p>
<a
className='intro-links'
@@ -346,7 +346,7 @@ export default class PostList extends React.Component {
return (
<div className='channel-intro'>
- <p className='channel-intro-text'>{'This is the start of your private message history with this teammate. Private messages and files shared here are not shown to people outside this area.'}</p>
+ <p className='channel-intro-text'>{'This is the start of your direct message history with this teammate. Direct messages and files shared here are not shown to people outside this area.'}</p>
</div>
);
}
diff --git a/web/react/components/post_list_container.jsx b/web/react/components/post_list_container.jsx
index 0815ac883..e59d85d41 100644
--- a/web/react/components/post_list_container.jsx
+++ b/web/react/components/post_list_container.jsx
@@ -49,6 +49,7 @@ export default class PostListContainer extends React.Component {
for (let i = 0; i <= this.state.postLists.length - 1; i++) {
postListCtls.push(
<PostList
+ key={'postlistkey' + i}
channelId={postLists[i]}
isActive={postLists[i] === channelId}
/>
diff --git a/web/react/components/register_app_modal.jsx b/web/react/components/register_app_modal.jsx
index 3dd5c094e..473ff3f91 100644
--- a/web/react/components/register_app_modal.jsx
+++ b/web/react/components/register_app_modal.jsx
@@ -228,7 +228,7 @@ export default class RegisterAppModal extends React.Component {
data-dismiss='modal'
aria-label='Close'
>
- <span aria-hidden='true'>{'x'}</span>
+ <span aria-hidden='true'>{'×'}</span>
</button>
<h4
className='modal-title'
diff --git a/web/react/components/rhs_comment.jsx b/web/react/components/rhs_comment.jsx
index fe31ac381..5b4694eb1 100644
--- a/web/react/components/rhs_comment.jsx
+++ b/web/react/components/rhs_comment.jsx
@@ -56,7 +56,6 @@ export default class RhsComment extends React.Component {
}
parseEmojis() {
twemoji.parse(React.findDOMNode(this), {size: Constants.EMOJI_SIZE});
- global.window.emojify.run(React.findDOMNode(this.refs.message_holder));
}
componentDidMount() {
this.parseEmojis();
@@ -114,14 +113,7 @@ export default class RhsComment extends React.Component {
var ownerOptions;
if (isOwner && post.state !== Constants.POST_FAILED && post.state !== Constants.POST_LOADING) {
ownerOptions = (
- <div
- className='dropdown'
- onClick={
- function scroll() {
- $('.post-list-holder-by-time').scrollTop($('.post-list-holder-by-time').scrollTop() + 50);
- }
- }
- >
+ <div className='dropdown'>
<a
href='#'
className='dropdown-toggle theme'
@@ -171,7 +163,6 @@ export default class RhsComment extends React.Component {
fileAttachment = (
<FileAttachmentList
filenames={post.filenames}
- modalId={'rhs_comment_view_image_modal_' + post.id}
channelId={post.channel_id}
userId={post.user_id}
/>
@@ -194,10 +185,7 @@ export default class RhsComment extends React.Component {
<strong><UserProfile userId={post.user_id} /></strong>
</li>
<li className='post-header-col'>
- <time
- className='post-profile-time'
- title={new Date(post.create_at).toString()}
- >
+ <time className='post-profile-time'>
{Utils.displayCommentDateTime(post.create_at)}
</time>
</li>
diff --git a/web/react/components/rhs_header_post.jsx b/web/react/components/rhs_header_post.jsx
index 5156ec4d7..f55c4095e 100644
--- a/web/react/components/rhs_header_post.jsx
+++ b/web/react/components/rhs_header_post.jsx
@@ -65,6 +65,7 @@ export default class RhsHeaderPost extends React.Component {
aria-label='Close'
onClick={this.handleClose}
>
+ <i className='fa fa-sign-out'/>
</button>
</div>
);
diff --git a/web/react/components/rhs_root_post.jsx b/web/react/components/rhs_root_post.jsx
index 2ea697c5b..13ab0c982 100644
--- a/web/react/components/rhs_root_post.jsx
+++ b/web/react/components/rhs_root_post.jsx
@@ -20,7 +20,6 @@ export default class RhsRootPost extends React.Component {
}
parseEmojis() {
twemoji.parse(React.findDOMNode(this), {size: Constants.EMOJI_SIZE});
- global.window.emojify.run(React.findDOMNode(this.refs.message_holder));
}
componentDidMount() {
this.parseEmojis();
@@ -54,7 +53,7 @@ export default class RhsRootPost extends React.Component {
var channelName;
if (channel) {
if (channel.type === 'D') {
- channelName = 'Private Message';
+ channelName = 'Direct Message';
} else {
channelName = channel.display_name;
}
@@ -112,7 +111,6 @@ export default class RhsRootPost extends React.Component {
fileAttachment = (
<FileAttachmentList
filenames={post.filenames}
- modalId={'rhs_view_image_modal_' + post.id}
channelId={post.channel_id}
userId={post.user_id}
/>
@@ -134,10 +132,7 @@ export default class RhsRootPost extends React.Component {
<ul className='post-header'>
<li className='post-header-col'><strong><UserProfile userId={post.user_id} /></strong></li>
<li className='post-header-col'>
- <time
- className='post-profile-time'
- title={new Date(post.create_at).toString()}
- >
+ <time className='post-profile-time'>
{utils.displayCommentDateTime(post.create_at)}
</time>
</li>
diff --git a/web/react/components/search_results_header.jsx b/web/react/components/search_results_header.jsx
index 694f0c55d..4e8a3ef10 100644
--- a/web/react/components/search_results_header.jsx
+++ b/web/react/components/search_results_header.jsx
@@ -50,6 +50,7 @@ export default class SearchResultsHeader extends React.Component {
title='Close'
onClick={this.handleClose}
>
+ <i className='fa fa-sign-out'/>
</button>
</div>
);
diff --git a/web/react/components/search_results_item.jsx b/web/react/components/search_results_item.jsx
index 0e951f5c6..32b521560 100644
--- a/web/react/components/search_results_item.jsx
+++ b/web/react/components/search_results_item.jsx
@@ -64,7 +64,7 @@ export default class SearchResultsItem extends React.Component {
if (channel) {
channelName = channel.display_name;
if (channel.type === 'D') {
- channelName = 'Private Message';
+ channelName = 'Direct Message';
}
}
diff --git a/web/react/components/settings_sidebar.jsx b/web/react/components/settings_sidebar.jsx
index e5cbd6e92..4c4675788 100644
--- a/web/react/components/settings_sidebar.jsx
+++ b/web/react/components/settings_sidebar.jsx
@@ -7,7 +7,8 @@ export default class SettingsSidebar extends React.Component {
this.handleClick = this.handleClick.bind(this);
}
- handleClick(tab) {
+ handleClick(tab, e) {
+ e.preventDefault();
this.props.updateTab(tab.name);
$('.settings-modal').addClass('display--content');
}
diff --git a/web/react/components/sidebar.jsx b/web/react/components/sidebar.jsx
index 87007edcc..14664ed4d 100644
--- a/web/react/components/sidebar.jsx
+++ b/web/react/components/sidebar.jsx
@@ -566,7 +566,7 @@ export default class Sidebar extends React.Component {
{privateChannelItems}
</ul>
<ul className='nav nav-pills nav-stacked'>
- <li><h4>Private Messages</h4></li>
+ <li><h4>Direct Messages</h4></li>
{directMessageItems}
{directMessageMore}
</ul>
diff --git a/web/react/components/sidebar_right_menu.jsx b/web/react/components/sidebar_right_menu.jsx
index 2671d560b..f1341d9d7 100644
--- a/web/react/components/sidebar_right_menu.jsx
+++ b/web/react/components/sidebar_right_menu.jsx
@@ -6,6 +6,10 @@ var client = require('../utils/client.jsx');
var utils = require('../utils/utils.jsx');
export default class SidebarRightMenu extends React.Component {
+ componentDidMount() {
+ $('.sidebar--left .dropdown-menu').perfectScrollbar();
+ }
+
constructor(props) {
super(props);
diff --git a/web/react/components/signup_team.jsx b/web/react/components/signup_team.jsx
index bf08e6508..4112138fa 100644
--- a/web/react/components/signup_team.jsx
+++ b/web/react/components/signup_team.jsx
@@ -12,38 +12,42 @@ export default class TeamSignUp extends React.Component {
this.updatePage = this.updatePage.bind(this);
- if (props.services.length === 1) {
- if (props.services[0] === Constants.EMAIL_SERVICE) {
- this.state = {page: 'email', service: ''};
- } else {
- this.state = {page: 'service', service: props.services[0]};
- }
- } else {
- this.state = {page: 'choose', service: ''};
+ var count = 0;
+
+ if (global.window.config.EnableSignUpWithEmail === 'true') {
+ count = count + 1;
+ }
+
+ if (global.window.config.EnableSignUpWithGitLab === 'true') {
+ count = count + 1;
+ }
+
+ if (count > 1) {
+ this.state = {page: 'choose'};
+ } else if (global.window.config.EnableSignUpWithEmail === 'true') {
+ this.state = {page: 'email'};
+ } else if (global.window.config.EnableSignUpWithGitLab === 'true') {
+ this.state = {page: 'gitlab'};
}
}
- updatePage(page, service) {
- this.setState({page: page, service: service});
+
+ updatePage(page) {
+ this.setState({page});
}
+
render() {
+ if (this.state.page === 'choose') {
+ return (
+ <ChoosePage
+ updatePage={this.updatePage}
+ />
+ );
+ }
+
if (this.state.page === 'email') {
return <EmailSignUpPage />;
- } else if (this.state.page === 'service' && this.state.service !== '') {
- return <SSOSignupPage service={this.state.service} />;
+ } else if (this.state.page === 'gitlab') {
+ return <SSOSignupPage service={Constants.GITLAB_SERVICE} />;
}
-
- return (
- <ChoosePage
- services={this.props.services}
- updatePage={this.updatePage}
- />
- );
}
}
-
-TeamSignUp.defaultProps = {
- services: []
-};
-TeamSignUp.propTypes = {
- services: React.PropTypes.array
-};
diff --git a/web/react/components/signup_user_complete.jsx b/web/react/components/signup_user_complete.jsx
index 19c3b2d22..495159efc 100644
--- a/web/react/components/signup_user_complete.jsx
+++ b/web/react/components/signup_user_complete.jsx
@@ -1,11 +1,10 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var utils = require('../utils/utils.jsx');
+var Utils = require('../utils/utils.jsx');
var client = require('../utils/client.jsx');
var UserStore = require('../stores/user_store.jsx');
var BrowserStore = require('../stores/browser_store.jsx');
-var Constants = require('../utils/constants.jsx');
export default class SignupUserComplete extends React.Component {
constructor(props) {
@@ -31,13 +30,26 @@ export default class SignupUserComplete extends React.Component {
handleSubmit(e) {
e.preventDefault();
+ const providedEmail = React.findDOMNode(this.refs.email).value.trim();
+ if (!providedEmail) {
+ this.setState({nameError: '', emailError: 'This field is required', passwordError: ''});
+ return;
+ }
+
+ if (!Utils.isEmail(providedEmail)) {
+ this.setState({nameError: '', emailError: 'Please enter a valid email address', passwordError: ''});
+ return;
+ }
+
+ this.state.user.email = providedEmail;
+
this.state.user.username = React.findDOMNode(this.refs.name).value.trim().toLowerCase();
if (!this.state.user.username) {
this.setState({nameError: 'This field is required', emailError: '', passwordError: '', serverError: ''});
return;
}
- var usernameError = utils.isValidUsername(this.state.user.username);
+ var usernameError = Utils.isValidUsername(this.state.user.username);
if (usernameError === 'Cannot use a reserved word as a username.') {
this.setState({nameError: 'This username is reserved, please choose a new one.', emailError: '', passwordError: '', serverError: ''});
return;
@@ -51,12 +63,6 @@ export default class SignupUserComplete extends React.Component {
return;
}
- this.state.user.email = React.findDOMNode(this.refs.email).value.trim();
- if (!this.state.user.email) {
- this.setState({nameError: '', emailError: 'This field is required', passwordError: ''});
- return;
- }
-
this.state.user.password = React.findDOMNode(this.refs.password).value.trim();
if (!this.state.user.password || this.state.user.password .length < 5) {
this.setState({nameError: '', emailError: '', passwordError: 'Please enter at least 5 characters', serverError: ''});
@@ -78,7 +84,7 @@ export default class SignupUserComplete extends React.Component {
if (this.props.hash > 0) {
BrowserStore.setGlobalItem(this.props.hash, JSON.stringify({wizard: 'finished'}));
}
- window.location.href = '/';
+ window.location.href = '/' + this.props.teamName + '/channels/town-square';
}.bind(this),
function emailLoginFailure(err) {
if (err.message === 'Login failed because email address has not been verified') {
@@ -161,11 +167,8 @@ export default class SignupUserComplete extends React.Component {
</div>
);
- // add options to log in using another service
- var authServices = JSON.parse(this.props.authServices);
-
var signupMessage = [];
- if (authServices.indexOf(Constants.GITLAB_SERVICE) >= 0) {
+ if (global.window.config.EnableSignUpWithGitLab === 'true') {
signupMessage.push(
<a
className='btn btn-custom-login gitlab'
@@ -178,7 +181,7 @@ export default class SignupUserComplete extends React.Component {
}
var emailSignup;
- if (authServices.indexOf(Constants.EMAIL_SERVICE) !== -1) {
+ if (global.window.config.EnableSignUpWithEmail === 'true') {
emailSignup = (
<div>
<div className='inner__content'>
@@ -262,7 +265,6 @@ SignupUserComplete.defaultProps = {
teamId: '',
email: '',
data: null,
- authServices: '',
teamDisplayName: ''
};
SignupUserComplete.propTypes = {
@@ -271,6 +273,5 @@ SignupUserComplete.propTypes = {
teamId: React.PropTypes.string,
email: React.PropTypes.string,
data: React.PropTypes.string,
- authServices: React.PropTypes.string,
teamDisplayName: React.PropTypes.string
};
diff --git a/web/react/components/team_feature_tab.jsx b/web/react/components/team_feature_tab.jsx
deleted file mode 100644
index 3251746b8..000000000
--- a/web/react/components/team_feature_tab.jsx
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
-// See License.txt for license information.
-
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
-
-var Client = require('../utils/client.jsx');
-var AsyncClient = require('../utils/async_client.jsx');
-
-export default class FeatureTab extends React.Component {
- constructor(props) {
- super(props);
-
- this.submitValetFeature = this.submitValetFeature.bind(this);
- this.handleValetRadio = this.handleValetRadio.bind(this);
- this.onUpdateSection = this.onUpdateSection.bind(this);
- this.setupInitialState = this.setupInitialState.bind(this);
-
- this.state = this.setupInitialState();
- }
- componentWillReceiveProps(newProps) {
- var team = newProps.team;
-
- var allowValet = 'false';
- if (team && team.allow_valet) {
- allowValet = 'true';
- }
-
- this.setState({allowValet: allowValet});
- }
- submitValetFeature() {
- var data = {};
- data.allow_valet = this.state.allowValet;
-
- Client.updateValetFeature(data,
- function success() {
- this.props.updateSection('');
- AsyncClient.getMyTeam();
- }.bind(this),
- function fail(err) {
- var state = this.setupInitialState();
- state.serverError = err;
- this.setState(state);
- }.bind(this)
- );
- }
- handleValetRadio(val) {
- this.setState({allowValet: val});
- React.findDOMNode(this.refs.wrapper).focus();
- }
- onUpdateSection(e) {
- e.preventDefault();
- if (this.props.activeSection === 'valet') {
- this.props.updateSection('');
- } else {
- this.props.updateSection('valet');
- }
- }
- setupInitialState() {
- var allowValet;
- var team = this.props.team;
-
- if (team && team.allow_valet) {
- allowValet = 'true';
- } else {
- allowValet = 'false';
- }
-
- return {allowValet: allowValet};
- }
- render() {
- var clientError = null;
- var serverError = null;
- if (this.state.clientError) {
- clientError = this.state.clientError;
- }
- if (this.state.serverError) {
- serverError = this.state.serverError;
- }
-
- var valetSection;
-
- if (this.props.activeSection === 'valet') {
- var valetActive = [false, false];
- if (this.state.allowValet === 'false') {
- valetActive[1] = true;
- } else {
- valetActive[0] = true;
- }
-
- let inputs = [];
-
- inputs.push(
- <div key='teamValetSetting'>
- <div className='radio'>
- <label>
- <input
- type='radio'
- checked={valetActive[0]}
- onChange={this.handleValetRadio.bind(this, 'true')}
- >
- On
- </input>
- </label>
- <br/>
- </div>
- <div className='radio'>
- <label>
- <input
- type='radio'
- checked={valetActive[1]}
- onChange={this.handleValetRadio.bind(this, 'false')}
- >
- Off
- </input>
- </label>
- <br/>
- </div>
- <div><br/>Valet is a preview feature for enabling a non-user account limited to basic member permissions that can be manipulated by 3rd parties.<br/><br/>IMPORTANT: The preview version of Valet should not be used without a secure connection and a trusted 3rd party, since user credentials are used to connect. OAuth2 will be used in the final release.</div>
- </div>
- );
-
- valetSection = (
- <SettingItemMax
- title='Valet (Preview - EXPERTS ONLY)'
- inputs={inputs}
- submit={this.submitValetFeature}
- server_error={serverError}
- client_error={clientError}
- updateSection={this.onUpdateSection}
- />
- );
- } else {
- var describe = '';
- if (this.state.allowValet === 'false') {
- describe = 'Off';
- } else {
- describe = 'On';
- }
-
- valetSection = (
- <SettingItemMin
- title='Valet (Preview - EXPERTS ONLY)'
- describe={describe}
- updateSection={this.onUpdateSection}
- />
- );
- }
-
- return (
- <div>
- <div className='modal-header'>
- <button
- type='button'
- className='close'
- data-dismiss='modal'
- aria-label='Close'
- >
- <span aria-hidden='true'>&times;</span>
- </button>
- <h4
- className='modal-title'
- ref='title'
- >
- <i className='modal-back'></i>Advanced Features
- </h4>
- </div>
- <div
- ref='wrapper'
- className='user-settings'
- >
- <h3 className='tab-header'>Advanced Features</h3>
- <div className='divider-dark first'/>
- {valetSection}
- <div className='divider-dark'/>
- </div>
- </div>
- );
- }
-}
-
-FeatureTab.defaultProps = {
- team: {},
- activeSection: ''
-};
-FeatureTab.propTypes = {
- updateSection: React.PropTypes.func.isRequired,
- team: React.PropTypes.object.isRequired,
- activeSection: React.PropTypes.string.isRequired
-};
diff --git a/web/react/components/team_import_tab.jsx b/web/react/components/team_import_tab.jsx
index 8315430e4..79f03510f 100644
--- a/web/react/components/team_import_tab.jsx
+++ b/web/react/components/team_import_tab.jsx
@@ -35,7 +35,7 @@ export default class TeamImportTab extends React.Component {
var uploadHelpText = (
<div>
<p>{'Slack does not allow you to export files, images, private groups or direct messages stored in Slack. Therefore, Slack import to Mattermost only supports importing of text messages in your Slack team\'\s public channels.'}</p>
- <p>{'The Slack import to Mattermost is in "Preview". Slack bot posts do not yet import.'}</p>
+ <p>{'The Slack import to Mattermost is in "Preview". Slack bot posts do not yet import and Slack @mentions are not currently supported.'}</p>
</div>
);
diff --git a/web/react/components/team_settings.jsx b/web/react/components/team_settings.jsx
index 396521af9..e91aa20bc 100644
--- a/web/react/components/team_settings.jsx
+++ b/web/react/components/team_settings.jsx
@@ -4,7 +4,6 @@
var TeamStore = require('../stores/team_store.jsx');
var ImportTab = require('./team_import_tab.jsx');
var ExportTab = require('./team_export_tab.jsx');
-var FeatureTab = require('./team_feature_tab.jsx');
var GeneralTab = require('./team_general_tab.jsx');
var Utils = require('../utils/utils.jsx');
@@ -25,7 +24,7 @@ export default class TeamSettings extends React.Component {
onChange() {
var team = TeamStore.getCurrent();
if (!Utils.areStatesEqual(this.state.team, team)) {
- this.setState({team: team});
+ this.setState({team});
}
}
render() {
@@ -43,17 +42,6 @@ export default class TeamSettings extends React.Component {
</div>
);
break;
- case 'feature':
- result = (
- <div>
- <FeatureTab
- team={this.state.team}
- activeSection={this.props.activeSection}
- updateSection={this.props.updateSection}
- />
- </div>
- );
- break;
case 'import':
result = (
<div>
diff --git a/web/react/components/team_settings_modal.jsx b/web/react/components/team_settings_modal.jsx
index 0513c811f..a96aadccf 100644
--- a/web/react/components/team_settings_modal.jsx
+++ b/web/react/components/team_settings_modal.jsx
@@ -20,8 +20,8 @@ export default class TeamSettingsModal extends React.Component {
$('body').on('click', '.modal-back', function handleBackClick() {
$(this).closest('.modal-dialog').removeClass('display--content');
});
- $('body').on('click', '.modal-header .close', function handleCloseClick() {
- setTimeout(function removeContent() {
+ $('body').on('click', '.modal-header .close', () => {
+ setTimeout(() => {
$('.modal-dialog.display--content').removeClass('display--content');
}, 500);
});
@@ -33,11 +33,12 @@ export default class TeamSettingsModal extends React.Component {
this.setState({activeSection: section});
}
render() {
- let tabs = [];
+ const tabs = [];
tabs.push({name: 'general', uiName: 'General', icon: 'glyphicon glyphicon-cog'});
tabs.push({name: 'import', uiName: 'Import', icon: 'glyphicon glyphicon-upload'});
- tabs.push({name: 'export', uiName: 'Export', icon: 'glyphicon glyphicon-download'});
- tabs.push({name: 'feature', uiName: 'Advanced', icon: 'glyphicon glyphicon-wrench'});
+
+ // To enable export uncomment this line
+ //tabs.push({name: 'export', uiName: 'Export', icon: 'glyphicon glyphicon-download'});
return (
<div
@@ -63,7 +64,7 @@ export default class TeamSettingsModal extends React.Component {
className='modal-title'
ref='title'
>
- Team Settings
+ {'Team Settings'}
</h4>
</div>
<div className='modal-body'>
diff --git a/web/react/components/team_signup_choose_auth.jsx b/web/react/components/team_signup_choose_auth.jsx
index d3107c5c7..b8264b887 100644
--- a/web/react/components/team_signup_choose_auth.jsx
+++ b/web/react/components/team_signup_choose_auth.jsx
@@ -1,8 +1,6 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var Constants = require('../utils/constants.jsx');
-
export default class ChooseAuthPage extends React.Component {
constructor(props) {
super(props);
@@ -10,7 +8,7 @@ export default class ChooseAuthPage extends React.Component {
}
render() {
var buttons = [];
- if (this.props.services.indexOf(Constants.GITLAB_SERVICE) !== -1) {
+ if (global.window.config.EnableSignUpWithGitLab === 'true') {
buttons.push(
<a
className='btn btn-custom-login gitlab btn-full'
@@ -18,17 +16,17 @@ export default class ChooseAuthPage extends React.Component {
onClick={
function clickGit(e) {
e.preventDefault();
- this.props.updatePage('service', Constants.GITLAB_SERVICE);
+ this.props.updatePage('gitlab');
}.bind(this)
}
>
<span className='icon' />
- <span>Create new team with GitLab Account</span>
+ <span>{'Create new team with GitLab Account'}</span>
</a>
);
}
- if (this.props.services.indexOf(Constants.EMAIL_SERVICE) !== -1) {
+ if (global.window.config.EnableSignUpWithEmail === 'true') {
buttons.push(
<a
className='btn btn-custom-login email btn-full'
@@ -36,18 +34,18 @@ export default class ChooseAuthPage extends React.Component {
onClick={
function clickEmail(e) {
e.preventDefault();
- this.props.updatePage('email', '');
+ this.props.updatePage('email');
}.bind(this)
}
>
<span className='fa fa-envelope' />
- <span>Create new team with email address</span>
+ <span>{'Create new team with email address'}</span>
</a>
);
}
if (buttons.length === 0) {
- buttons = <span>No sign-up methods configured, please contact your system administrator.</span>;
+ buttons = <span>{'No sign-up methods configured, please contact your system administrator.'}</span>;
}
return (
@@ -61,10 +59,6 @@ export default class ChooseAuthPage extends React.Component {
}
}
-ChooseAuthPage.defaultProps = {
- services: []
-};
ChooseAuthPage.propTypes = {
- services: React.PropTypes.array,
updatePage: React.PropTypes.func
};
diff --git a/web/react/components/team_signup_password_page.jsx b/web/react/components/team_signup_password_page.jsx
index b26d9f6ce..105e4817a 100644
--- a/web/react/components/team_signup_password_page.jsx
+++ b/web/react/components/team_signup_password_page.jsx
@@ -53,7 +53,7 @@ export default class TeamSignupPasswordPage extends React.Component {
props.state.wizard = 'finished';
props.updateParent(props.state, true);
- window.location.href = '/';
+ window.location.href = '/' + teamSignup.team.name + '/channels/town-square';
}.bind(this),
function loginFail(err) {
if (err.message === 'Login failed because email address has not been verified') {
diff --git a/web/react/components/team_signup_send_invites_page.jsx b/web/react/components/team_signup_send_invites_page.jsx
index 41ac98303..524bd5b50 100644
--- a/web/react/components/team_signup_send_invites_page.jsx
+++ b/web/react/components/team_signup_send_invites_page.jsx
@@ -13,7 +13,7 @@ export default class TeamSignupSendInvitesPage extends React.Component {
this.submitSkip = this.submitSkip.bind(this);
this.keySubmit = this.keySubmit.bind(this);
this.state = {
- emailEnabled: !global.window.config.ByPassEmail
+ emailEnabled: global.window.config.SendEmailNotifications === 'true'
};
if (!this.state.emailEnabled) {
diff --git a/web/react/components/team_signup_with_sso.jsx b/web/react/components/team_signup_with_sso.jsx
index 2849b4cbb..a4972dd8d 100644
--- a/web/react/components/team_signup_with_sso.jsx
+++ b/web/react/components/team_signup_with_sso.jsx
@@ -42,7 +42,7 @@ export default class SSOSignUpPage extends React.Component {
if (data.follow_link) {
window.location.href = data.follow_link;
} else {
- window.location.href = '/';
+ window.location.href = '/' + team.name + '/channels/town-square';
}
},
function fail(err) {
diff --git a/web/react/components/textbox.jsx b/web/react/components/textbox.jsx
index ea8126bec..5f5316013 100644
--- a/web/react/components/textbox.jsx
+++ b/web/react/components/textbox.jsx
@@ -5,7 +5,6 @@ const AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
const PostStore = require('../stores/post_store.jsx');
const CommandList = require('./command_list.jsx');
const ErrorStore = require('../stores/error_store.jsx');
-const AsyncClient = require('../utils/async_client.jsx');
const Utils = require('../utils/utils.jsx');
const Constants = require('../utils/constants.jsx');
@@ -18,7 +17,6 @@ export default class Textbox extends React.Component {
this.getStateFromStores = this.getStateFromStores.bind(this);
this.onListenerChange = this.onListenerChange.bind(this);
this.onRecievedError = this.onRecievedError.bind(this);
- this.onTimerInterrupt = this.onTimerInterrupt.bind(this);
this.updateMentionTab = this.updateMentionTab.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
@@ -35,8 +33,7 @@ export default class Textbox extends React.Component {
this.state = {
mentionText: '-1',
mentions: [],
- connection: '',
- timerInterrupt: null
+ connection: ''
};
this.caret = -1;
@@ -44,6 +41,7 @@ export default class Textbox extends React.Component {
this.doProcessMentions = false;
this.mentions = [];
}
+
getStateFromStores() {
const error = ErrorStore.getLastError();
@@ -53,6 +51,7 @@ export default class Textbox extends React.Component {
return {message: null};
}
+
componentDidMount() {
PostStore.addAddMentionListener(this.onListenerChange);
ErrorStore.addChangeListener(this.onRecievedError);
@@ -60,46 +59,28 @@ export default class Textbox extends React.Component {
this.resize();
this.updateMentionTab(null);
}
+
componentWillUnmount() {
PostStore.removeAddMentionListener(this.onListenerChange);
ErrorStore.removeChangeListener(this.onRecievedError);
}
+
onListenerChange(id, username) {
if (id === this.props.id) {
this.addMention(username);
}
}
- onRecievedError() {
- const errorState = this.getStateFromStores();
- if (this.state.timerInterrupt !== null) {
- window.clearInterval(this.state.timerInterrupt);
- this.setState({timerInterrupt: null});
- }
+ onRecievedError() {
+ const errorState = ErrorStore.getLastError();
- if (errorState.message === 'There appears to be a problem with your internet connection') {
+ if (errorState && errorState.connErrorCount > 0) {
this.setState({connection: 'bad-connection'});
- const timerInterrupt = window.setInterval(this.onTimerInterrupt, 5000);
- this.setState({timerInterrupt: timerInterrupt});
} else {
this.setState({connection: ''});
}
}
- onTimerInterrupt() {
- // Since these should only happen when you have no connection and slightly briefly after any
- // performance hit should not matter
- if (this.state.connection === 'bad-connection') {
- AppDispatcher.handleServerAction({
- type: ActionTypes.RECIEVED_ERROR,
- err: null
- });
-
- AsyncClient.updateLastViewedAt();
- }
- window.clearInterval(this.state.timerInterrupt);
- this.setState({timerInterrupt: null});
- }
componentDidUpdate() {
if (this.caret >= 0) {
Utils.setCaretPosition(React.findDOMNode(this.refs.message), this.caret);
@@ -111,6 +92,7 @@ export default class Textbox extends React.Component {
}
this.resize();
}
+
componentWillReceiveProps(nextProps) {
if (!this.addedMention) {
this.checkForNewMention(nextProps.messageText);
@@ -122,19 +104,22 @@ export default class Textbox extends React.Component {
this.addedMention = false;
this.refs.commands.getSuggestedCommands(nextProps.messageText);
}
+
updateMentionTab(mentionText) {
// using setTimeout so dispatch isn't called during an in progress dispatch
- setTimeout(function updateMentionTabAfterTimeout() {
+ setTimeout(() => {
AppDispatcher.handleViewAction({
type: ActionTypes.RECIEVED_MENTION_DATA,
id: this.props.id,
mention_text: mentionText
});
- }.bind(this), 1);
+ }, 1);
}
+
handleChange() {
this.props.onUserInput(React.findDOMNode(this.refs.message).value);
}
+
handleKeyPress(e) {
const text = React.findDOMNode(this.refs.message).value;
@@ -157,6 +142,7 @@ export default class Textbox extends React.Component {
this.props.onKeyPress(e);
}
+
handleKeyDown(e) {
if (Utils.getSelectedText(React.findDOMNode(this.refs.message)) !== '') {
this.doProcessMentions = true;
@@ -166,6 +152,7 @@ export default class Textbox extends React.Component {
this.handleBackspace(e);
}
}
+
handleBackspace() {
const text = React.findDOMNode(this.refs.message).value;
if (text.indexOf('/') === 0) {
@@ -185,6 +172,7 @@ export default class Textbox extends React.Component {
this.doProcessMentions = true;
}
}
+
checkForNewMention(text) {
const caret = Utils.getCaretPosition(React.findDOMNode(this.refs.message));
@@ -211,6 +199,7 @@ export default class Textbox extends React.Component {
const name = preText.substring(atIndex + 1, preText.length).toLowerCase();
this.updateMentionTab(name);
}
+
addMention(name) {
const caret = Utils.getCaretPosition(React.findDOMNode(this.refs.message));
@@ -233,11 +222,13 @@ export default class Textbox extends React.Component {
this.props.onUserInput(`${prefix}@${name} ${suffix}`);
}
+
addCommand(cmd) {
const elm = React.findDOMNode(this.refs.message);
elm.value = cmd;
this.handleChange();
}
+
resize() {
const e = React.findDOMNode(this.refs.message);
const w = React.findDOMNode(this.refs.wrapper);
@@ -264,21 +255,25 @@ export default class Textbox extends React.Component {
this.props.onHeightChange();
}
}
+
handleFocus() {
const elm = React.findDOMNode(this.refs.message);
if (elm.title === elm.value) {
elm.value = '';
}
}
+
handleBlur() {
const elm = React.findDOMNode(this.refs.message);
if (elm.value === '') {
elm.value = elm.title;
}
}
+
handlePaste() {
this.doProcessMentions = true;
}
+
render() {
return (
<div
diff --git a/web/react/components/user_profile.jsx b/web/react/components/user_profile.jsx
index 7cfac69e7..c5d028d31 100644
--- a/web/react/components/user_profile.jsx
+++ b/web/react/components/user_profile.jsx
@@ -57,7 +57,7 @@ export default class UserProfile extends React.Component {
}
var dataContent = '<img class="user-popover__image" src="/api/v1/users/' + this.state.profile.id + '/image?time=' + this.state.profile.update_at + '" height="128" width="128" />';
- if (!global.window.config.ShowEmailAddress) {
+ if (!global.window.config.ShowEmailAddress === 'true') {
dataContent += '<div class="text-nowrap">Email not shared</div>';
} else {
dataContent += '<div data-toggle="tooltip" title="' + this.state.profile.email + '"><a href="mailto:' + this.state.profile.email + '" class="text-nowrap text-lowercase user-popover__email">' + this.state.profile.email + '</a></div>';
diff --git a/web/react/components/user_settings/custom_theme_chooser.jsx b/web/react/components/user_settings/custom_theme_chooser.jsx
new file mode 100644
index 000000000..c680d75d1
--- /dev/null
+++ b/web/react/components/user_settings/custom_theme_chooser.jsx
@@ -0,0 +1,111 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Constants = require('../../utils/constants.jsx');
+
+export default class CustomThemeChooser extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.onPickerChange = this.onPickerChange.bind(this);
+ this.onInputChange = this.onInputChange.bind(this);
+ this.pasteBoxChange = this.pasteBoxChange.bind(this);
+
+ this.state = {};
+ }
+ componentDidMount() {
+ $('.color-picker').colorpicker().on('changeColor', this.onPickerChange);
+ }
+ onPickerChange(e) {
+ const theme = this.props.theme;
+ theme[e.target.id] = e.color.toHex();
+ theme.type = 'custom';
+ this.props.updateTheme(theme);
+ }
+ onInputChange(e) {
+ const theme = this.props.theme;
+ theme[e.target.parentNode.id] = e.target.value;
+ theme.type = 'custom';
+ this.props.updateTheme(theme);
+ }
+ pasteBoxChange(e) {
+ const text = e.target.value;
+
+ if (text.length === 0) {
+ return;
+ }
+
+ const colors = text.split(',');
+
+ const theme = {type: 'custom'};
+ let index = 0;
+ Constants.THEME_ELEMENTS.forEach((element) => {
+ if (index < colors.length) {
+ theme[element.id] = colors[index];
+ }
+ index++;
+ });
+
+ this.props.updateTheme(theme);
+ }
+ render() {
+ const theme = this.props.theme;
+
+ const elements = [];
+ let colors = '';
+ Constants.THEME_ELEMENTS.forEach((element, index) => {
+ elements.push(
+ <div
+ className='col-sm-4 form-group'
+ key={'custom-theme-key' + index}
+ >
+ <label className='custom-label'>{element.uiName}</label>
+ <div
+ className='input-group color-picker'
+ id={element.id}
+ >
+ <input
+ className='form-control'
+ type='text'
+ defaultValue={theme[element.id]}
+ onChange={this.onInputChange}
+ />
+ <span className='input-group-addon'><i></i></span>
+ </div>
+ </div>
+ );
+
+ colors += theme[element.id] + ',';
+ });
+
+ const pasteBox = (
+ <div className='col-sm-12'>
+ <label className='custom-label'>
+ {'Copy and paste to share theme colors:'}
+ </label>
+ <input
+ type='text'
+ className='form-control'
+ value={colors}
+ onChange={this.pasteBoxChange}
+ />
+ </div>
+ );
+
+ return (
+ <div>
+ <div className='row form-group'>
+ {elements}
+ </div>
+ <div className='row'>
+ {pasteBox}
+ </div>
+ </div>
+ );
+ }
+}
+
+CustomThemeChooser.propTypes = {
+ theme: React.PropTypes.object.isRequired,
+ updateTheme: React.PropTypes.func.isRequired
+};
diff --git a/web/react/components/user_settings/import_theme_modal.jsx b/web/react/components/user_settings/import_theme_modal.jsx
new file mode 100644
index 000000000..48be83afe
--- /dev/null
+++ b/web/react/components/user_settings/import_theme_modal.jsx
@@ -0,0 +1,179 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+const UserStore = require('../../stores/user_store.jsx');
+const Utils = require('../../utils/utils.jsx');
+const Client = require('../../utils/client.jsx');
+const Modal = ReactBootstrap.Modal;
+
+const AppDispatcher = require('../../dispatcher/app_dispatcher.jsx');
+const Constants = require('../../utils/constants.jsx');
+const ActionTypes = Constants.ActionTypes;
+
+export default class ImportThemeModal extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.updateShow = this.updateShow.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.handleChange = this.handleChange.bind(this);
+
+ this.state = {
+ inputError: '',
+ show: false
+ };
+ }
+ componentDidMount() {
+ UserStore.addImportModalListener(this.updateShow);
+ }
+ componentWillUnmount() {
+ UserStore.removeImportModalListener(this.updateShow);
+ }
+ updateShow(show) {
+ this.setState({show});
+ }
+ handleSubmit(e) {
+ e.preventDefault();
+
+ const text = React.findDOMNode(this.refs.input).value;
+
+ if (!this.isInputValid(text)) {
+ this.setState({inputError: 'Invalid format, please try copying and pasting in again.'});
+ return;
+ }
+
+ const colors = text.split(',');
+ const theme = {type: 'custom'};
+
+ theme.sidebarBg = colors[0];
+ theme.sidebarText = colors[5];
+ theme.sidebarUnreadText = colors[5];
+ theme.sidebarTextHoverBg = colors[4];
+ theme.sidebarTextHoverColor = colors[5];
+ theme.sidebarTextActiveBg = colors[2];
+ theme.sidebarTextActiveColor = colors[3];
+ theme.sidebarHeaderBg = colors[1];
+ theme.sidebarHeaderTextColor = colors[5];
+ theme.onlineIndicator = colors[6];
+ theme.mentionBj = colors[7];
+ theme.mentionColor = '#ffffff';
+ theme.centerChannelBg = '#ffffff';
+ theme.centerChannelColor = '#333333';
+ theme.linkColor = '#2389d7';
+ theme.buttonBg = '#26a970';
+ theme.buttonColor = '#ffffff';
+
+ let user = UserStore.getCurrentUser();
+ user.theme_props = theme;
+
+ Client.updateUser(user,
+ (data) => {
+ AppDispatcher.handleServerAction({
+ type: ActionTypes.RECIEVED_ME,
+ me: data
+ });
+
+ this.setState({show: false});
+ Utils.applyTheme(theme);
+ $('#user_settings').modal('show');
+ },
+ (err) => {
+ var state = this.getStateFromStores();
+ state.serverError = err;
+ this.setState(state);
+ }
+ );
+ }
+ isInputValid(text) {
+ if (text.length === 0) {
+ return false;
+ }
+
+ if (text.indexOf(' ') !== -1) {
+ return false;
+ }
+
+ if (text.length > 0 && text.indexOf(',') === -1) {
+ return false;
+ }
+
+ if (text.length > 0) {
+ const colors = text.split(',');
+
+ if (colors.length !== 8) {
+ return false;
+ }
+
+ for (let i = 0; i < colors.length; i++) {
+ if (colors[i].length !== 7 && colors[i].length !== 4) {
+ return false;
+ }
+
+ if (colors[i].charAt(0) !== '#') {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+ handleChange(e) {
+ if (this.isInputValid(e.target.value)) {
+ this.setState({inputError: null});
+ } else {
+ this.setState({inputError: 'Invalid format, please try copying and pasting in again.'});
+ }
+ }
+ render() {
+ return (
+ <span>
+ <Modal
+ show={this.state.show}
+ onHide={() => this.setState({show: false})}
+ >
+ <Modal.Header closeButton={true}>
+ <Modal.Title>{'Import Slack Theme'}</Modal.Title>
+ </Modal.Header>
+ <form
+ role='form'
+ className='form-horizontal'
+ >
+ <Modal.Body>
+ <p>
+ {'To import a theme, go to a Slack team and look for “”Preferences” -> Sidebar Theme”. Open the custom theme option, copy the theme color values and paste them here:'}
+ </p>
+ <div className='form-group less'>
+ <div className='col-sm-9'>
+ <input
+ ref='input'
+ type='text'
+ className='form-control'
+ onChange={this.handleChange}
+ />
+ {this.state.inputError}
+ </div>
+ </div>
+ </Modal.Body>
+ <Modal.Footer>
+ <button
+ type='button'
+ className='btn btn-default'
+ onClick={() => this.setState({show: false})}
+ >
+ {'Cancel'}
+ </button>
+ <button
+ onClick={this.handleSubmit}
+ type='submit'
+ className='btn btn-primary'
+ tabIndex='3'
+ >
+ {'Submit'}
+ </button>
+ </Modal.Footer>
+ </form>
+ </Modal>
+ </span>
+ );
+ }
+}
diff --git a/web/react/components/user_settings/manage_incoming_hooks.jsx b/web/react/components/user_settings/manage_incoming_hooks.jsx
new file mode 100644
index 000000000..1bbfbd162
--- /dev/null
+++ b/web/react/components/user_settings/manage_incoming_hooks.jsx
@@ -0,0 +1,174 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Client = require('../../utils/client.jsx');
+var Utils = require('../../utils/utils.jsx');
+var Constants = require('../../utils/constants.jsx');
+var ChannelStore = require('../../stores/channel_store.jsx');
+var LoadingScreen = require('../loading_screen.jsx');
+
+export default class ManageIncomingHooks extends React.Component {
+ constructor() {
+ super();
+
+ this.getHooks = this.getHooks.bind(this);
+ this.addNewHook = this.addNewHook.bind(this);
+ this.updateChannelId = this.updateChannelId.bind(this);
+
+ this.state = {hooks: [], channelId: ChannelStore.getByName(Constants.DEFAULT_CHANNEL).id, getHooksComplete: false};
+ }
+ componentDidMount() {
+ this.getHooks();
+ }
+ addNewHook() {
+ let hook = {}; //eslint-disable-line prefer-const
+ hook.channel_id = this.state.channelId;
+
+ Client.addIncomingHook(
+ hook,
+ (data) => {
+ let hooks = this.state.hooks;
+ if (!hooks) {
+ hooks = [];
+ }
+ hooks.push(data);
+ this.setState({hooks});
+ },
+ (err) => {
+ this.setState({serverError: err});
+ }
+ );
+ }
+ removeHook(id) {
+ let data = {}; //eslint-disable-line prefer-const
+ data.id = id;
+
+ Client.deleteIncomingHook(
+ data,
+ () => {
+ let hooks = this.state.hooks; //eslint-disable-line prefer-const
+ let index = -1;
+ for (let i = 0; i < hooks.length; i++) {
+ if (hooks[i].id === id) {
+ index = i;
+ break;
+ }
+ }
+
+ if (index !== -1) {
+ hooks.splice(index, 1);
+ }
+
+ this.setState({hooks});
+ },
+ (err) => {
+ this.setState({serverError: err});
+ }
+ );
+ }
+ getHooks() {
+ Client.listIncomingHooks(
+ (data) => {
+ let state = this.state; //eslint-disable-line prefer-const
+
+ if (data) {
+ state.hooks = data;
+ }
+
+ state.getHooksComplete = true;
+ this.setState(state);
+ },
+ (err) => {
+ this.setState({serverError: err});
+ }
+ );
+ }
+ updateChannelId(e) {
+ this.setState({channelId: e.target.value});
+ }
+ render() {
+ let serverError;
+ if (this.state.serverError) {
+ serverError = <label className='has-error'>{this.state.serverError}</label>;
+ }
+
+ const channels = ChannelStore.getAll();
+ let options = []; //eslint-disable-line prefer-const
+ channels.forEach((channel) => {
+ options.push(<option value={channel.id}>{channel.name}</option>);
+ });
+
+ let disableButton = '';
+ if (this.state.channelId === '') {
+ disableButton = ' disable';
+ }
+
+ let hooks = []; //eslint-disable-line prefer-const
+ this.state.hooks.forEach((hook) => {
+ const c = ChannelStore.get(hook.channel_id);
+ hooks.push(
+ <div className='font--small'>
+ <div className='padding-top x2 divider-light'></div>
+ <div className='padding-top x2'>
+ <strong>{'URL: '}</strong><span className='word-break--all'>{Utils.getWindowLocationOrigin() + '/hooks/' + hook.id}</span>
+ </div>
+ <div className='padding-top'>
+ <strong>{'Channel: '}</strong>{c.name}
+ </div>
+ <div className='padding-top'>
+ <a
+ className={'text-danger'}
+ href='#'
+ onClick={this.removeHook.bind(this, hook.id)}
+ >
+ {'Remove'}
+ </a>
+ </div>
+ </div>
+ );
+ });
+
+ let displayHooks;
+ if (!this.state.getHooksComplete) {
+ displayHooks = <LoadingScreen/>;
+ } else if (hooks.length > 0) {
+ displayHooks = hooks;
+ } else {
+ displayHooks = <label>{': None'}</label>;
+ }
+
+ const existingHooks = (
+ <div className='padding-top x2'>
+ <label className='control-label padding-top x2'>{'Existing incoming webhooks'}</label>
+ {displayHooks}
+ </div>
+ );
+
+ return (
+ <div key='addIncomingHook'>
+ <label className='control-label'>{'Add a new incoming webhook'}</label>
+ <div className='padding-top'>
+ <select
+ ref='channelName'
+ className='form-control'
+ value={this.state.channelId}
+ onChange={this.updateChannelId}
+ >
+ {options}
+ </select>
+ {serverError}
+ <div className='padding-top'>
+ <a
+ className={'btn btn-sm btn-primary' + disableButton}
+ href='#'
+ onClick={this.addNewHook}
+ >
+ {'Add'}
+ </a>
+ </div>
+ </div>
+ {existingHooks}
+ </div>
+ );
+ }
+}
diff --git a/web/react/components/user_settings/premade_theme_chooser.jsx b/web/react/components/user_settings/premade_theme_chooser.jsx
new file mode 100644
index 000000000..f8f916bd0
--- /dev/null
+++ b/web/react/components/user_settings/premade_theme_chooser.jsx
@@ -0,0 +1,58 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var Utils = require('../../utils/utils.jsx');
+var Constants = require('../../utils/constants.jsx');
+
+export default class PremadeThemeChooser extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {};
+ }
+ render() {
+ const theme = this.props.theme;
+
+ const premadeThemes = [];
+ for (const k in Constants.THEMES) {
+ if (Constants.THEMES.hasOwnProperty(k)) {
+ const premadeTheme = $.extend(true, {}, Constants.THEMES[k]);
+
+ let activeClass = '';
+ if (premadeTheme.type === theme.type) {
+ activeClass = 'active';
+ }
+
+ premadeThemes.push(
+ <div
+ className='col-sm-3 premade-themes'
+ key={'premade-theme-key' + k}
+ >
+ <div
+ className={activeClass}
+ onClick={() => this.props.updateTheme(premadeTheme)}
+ >
+ <label>
+ <img
+ className='img-responsive'
+ src={'/static/images/themes/' + premadeTheme.type.toLowerCase() + '.png'}
+ />
+ <div className='theme-label'>{Utils.toTitleCase(premadeTheme.type)}</div>
+ </label>
+ </div>
+ </div>
+ );
+ }
+ }
+
+ return (
+ <div className='row'>
+ {premadeThemes}
+ </div>
+ );
+ }
+}
+
+PremadeThemeChooser.propTypes = {
+ theme: React.PropTypes.object.isRequired,
+ updateTheme: React.PropTypes.func.isRequired
+};
diff --git a/web/react/components/user_settings.jsx b/web/react/components/user_settings/user_settings.jsx
index 48b499068..0eab333c4 100644
--- a/web/react/components/user_settings.jsx
+++ b/web/react/components/user_settings/user_settings.jsx
@@ -1,13 +1,14 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var UserStore = require('../stores/user_store.jsx');
-var utils = require('../utils/utils.jsx');
+var UserStore = require('../../stores/user_store.jsx');
+var utils = require('../../utils/utils.jsx');
var NotificationsTab = require('./user_settings_notifications.jsx');
var SecurityTab = require('./user_settings_security.jsx');
var GeneralTab = require('./user_settings_general.jsx');
var AppearanceTab = require('./user_settings_appearance.jsx');
var DeveloperTab = require('./user_settings_developer.jsx');
+var IntegrationsTab = require('./user_settings_integrations.jsx');
export default class UserSettings extends React.Component {
constructor(props) {
@@ -86,6 +87,17 @@ export default class UserSettings extends React.Component {
/>
</div>
);
+ } else if (this.props.activeTab === 'integrations') {
+ return (
+ <div>
+ <IntegrationsTab
+ user={this.state.user}
+ activeSection={this.props.activeSection}
+ updateSection={this.props.updateSection}
+ updateTab={this.props.updateTab}
+ />
+ </div>
+ );
}
return <div/>;
diff --git a/web/react/components/user_settings/user_settings_appearance.jsx b/web/react/components/user_settings/user_settings_appearance.jsx
new file mode 100644
index 000000000..4372069e7
--- /dev/null
+++ b/web/react/components/user_settings/user_settings_appearance.jsx
@@ -0,0 +1,236 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var UserStore = require('../../stores/user_store.jsx');
+var Client = require('../../utils/client.jsx');
+var Utils = require('../../utils/utils.jsx');
+
+const CustomThemeChooser = require('./custom_theme_chooser.jsx');
+const PremadeThemeChooser = require('./premade_theme_chooser.jsx');
+const AppDispatcher = require('../../dispatcher/app_dispatcher.jsx');
+const Constants = require('../../utils/constants.jsx');
+const ActionTypes = Constants.ActionTypes;
+
+export default class UserSettingsAppearance extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.onChange = this.onChange.bind(this);
+ this.submitTheme = this.submitTheme.bind(this);
+ this.updateTheme = this.updateTheme.bind(this);
+ this.handleClose = this.handleClose.bind(this);
+ this.handleImportModal = this.handleImportModal.bind(this);
+
+ this.state = this.getStateFromStores();
+
+ this.originalTheme = this.state.theme;
+ }
+ componentDidMount() {
+ UserStore.addChangeListener(this.onChange);
+
+ if (this.props.activeSection === 'theme') {
+ $(React.findDOMNode(this.refs[this.state.theme])).addClass('active-border');
+ }
+ $('#user_settings').on('hidden.bs.modal', this.handleClose);
+ }
+ componentDidUpdate() {
+ if (this.props.activeSection === 'theme') {
+ $('.color-btn').removeClass('active-border');
+ $(React.findDOMNode(this.refs[this.state.theme])).addClass('active-border');
+ }
+ }
+ componentWillUnmount() {
+ UserStore.removeChangeListener(this.onChange);
+ $('#user_settings').off('hidden.bs.modal', this.handleClose);
+ }
+ getStateFromStores() {
+ const user = UserStore.getCurrentUser();
+ let theme = null;
+
+ if ($.isPlainObject(user.theme_props) && !$.isEmptyObject(user.theme_props)) {
+ theme = user.theme_props;
+ } else {
+ theme = $.extend(true, {}, Constants.THEMES.default);
+ }
+
+ let type = 'premade';
+ if (theme.type === 'custom') {
+ type = 'custom';
+ }
+
+ return {theme, type};
+ }
+ onChange() {
+ const newState = this.getStateFromStores();
+
+ if (!Utils.areStatesEqual(this.state, newState)) {
+ this.setState(newState);
+ }
+ }
+ submitTheme(e) {
+ e.preventDefault();
+ var user = UserStore.getCurrentUser();
+ user.theme_props = this.state.theme;
+
+ Client.updateUser(user,
+ (data) => {
+ AppDispatcher.handleServerAction({
+ type: ActionTypes.RECIEVED_ME,
+ me: data
+ });
+
+ $('#user_settings').off('hidden.bs.modal', this.handleClose);
+ this.props.updateTab('general');
+ $('.ps-container.modal-body').scrollTop(0);
+ $('.ps-container.modal-body').perfectScrollbar('update');
+ $('#user_settings').modal('hide');
+ },
+ (err) => {
+ var state = this.getStateFromStores();
+ state.serverError = err;
+ this.setState(state);
+ }
+ );
+ }
+ updateTheme(theme) {
+ this.setState({theme});
+ Utils.applyTheme(theme);
+ }
+ updateType(type) {
+ this.setState({type});
+ }
+ handleClose() {
+ const state = this.getStateFromStores();
+ state.serverError = null;
+
+ Utils.applyTheme(state.theme);
+
+ this.setState(state);
+
+ $('.ps-container.modal-body').scrollTop(0);
+ $('.ps-container.modal-body').perfectScrollbar('update');
+ $('#user_settings').modal('hide');
+ }
+ handleImportModal() {
+ $('#user_settings').modal('hide');
+ AppDispatcher.handleViewAction({
+ type: ActionTypes.TOGGLE_IMPORT_THEME_MODAL,
+ value: true
+ });
+ }
+ render() {
+ var serverError;
+ if (this.state.serverError) {
+ serverError = this.state.serverError;
+ }
+
+ const displayCustom = this.state.type === 'custom';
+
+ let custom;
+ let premade;
+ if (displayCustom) {
+ custom = (
+ <CustomThemeChooser
+ theme={this.state.theme}
+ updateTheme={this.updateTheme}
+ />
+ );
+ } else {
+ premade = (
+ <PremadeThemeChooser
+ theme={this.state.theme}
+ updateTheme={this.updateTheme}
+ />
+ );
+ }
+
+ const themeUI = (
+ <div className='section-max appearance-section'>
+ <div className='col-sm-12'>
+ <div className='radio'>
+ <label>
+ <input type='radio'
+ checked={!displayCustom}
+ onChange={this.updateType.bind(this, 'premade')}
+ >
+ {'Theme Colors'}
+ </input>
+ </label>
+ <br/>
+ </div>
+ {premade}
+ <div className='radio'>
+ <label>
+ <input type='radio'
+ checked={displayCustom}
+ onChange={this.updateType.bind(this, 'custom')}
+ >
+ {'Custom Theme'}
+ </input>
+ </label>
+ <br/>
+ </div>
+ {custom}
+ <hr />
+ {serverError}
+ <a
+ className='btn btn-sm btn-primary'
+ href='#'
+ onClick={this.submitTheme}
+ >
+ {'Submit'}
+ </a>
+ <a
+ className='btn btn-sm theme'
+ href='#'
+ onClick={this.handleClose}
+ >
+ {'Cancel'}
+ </a>
+ </div>
+ </div>
+ );
+
+ return (
+ <div>
+ <div className='modal-header'>
+ <button
+ type='button'
+ className='close'
+ data-dismiss='modal'
+ aria-label='Close'
+ >
+ <span aria-hidden='true'>{'×'}</span>
+ </button>
+ <h4
+ className='modal-title'
+ ref='title'
+ >
+ <i className='modal-back'></i>{'Appearance Settings'}
+ </h4>
+ </div>
+ <div className='user-settings'>
+ <h3 className='tab-header'>{'Appearance Settings'}</h3>
+ <div className='divider-dark first'/>
+ {themeUI}
+ <div className='divider-dark'/>
+ </div>
+ <br/>
+ <a
+ className='theme'
+ onClick={this.handleImportModal}
+ >
+ {'Import from Slack'}
+ </a>
+ </div>
+ );
+ }
+}
+
+UserSettingsAppearance.defaultProps = {
+ activeSection: ''
+};
+UserSettingsAppearance.propTypes = {
+ activeSection: React.PropTypes.string,
+ updateTab: React.PropTypes.func
+};
diff --git a/web/react/components/user_settings_developer.jsx b/web/react/components/user_settings/user_settings_developer.jsx
index 1b04149dc..d9fb43902 100644
--- a/web/react/components/user_settings_developer.jsx
+++ b/web/react/components/user_settings/user_settings_developer.jsx
@@ -1,8 +1,8 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
+var SettingItemMin = require('../setting_item_min.jsx');
+var SettingItemMax = require('../setting_item_max.jsx');
export default class DeveloperTab extends React.Component {
constructor(props) {
@@ -64,7 +64,7 @@ export default class DeveloperTab extends React.Component {
data-dismiss='modal'
aria-label='Close'
>
- <span aria-hidden='true'>{'x'}</span>
+ <span aria-hidden='true'>{'×'}</span>
</button>
<h4
className='modal-title'
diff --git a/web/react/components/user_settings_general.jsx b/web/react/components/user_settings/user_settings_general.jsx
index 66cde6ca2..c1d4c4ab5 100644
--- a/web/react/components/user_settings_general.jsx
+++ b/web/react/components/user_settings/user_settings_general.jsx
@@ -1,13 +1,13 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var UserStore = require('../stores/user_store.jsx');
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
-var SettingPicture = require('./setting_picture.jsx');
-var client = require('../utils/client.jsx');
-var AsyncClient = require('../utils/async_client.jsx');
-var utils = require('../utils/utils.jsx');
+var UserStore = require('../../stores/user_store.jsx');
+var SettingItemMin = require('../setting_item_min.jsx');
+var SettingItemMax = require('../setting_item_max.jsx');
+var SettingPicture = require('../setting_picture.jsx');
+var client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var utils = require('../../utils/utils.jsx');
var assign = require('object-assign');
export default class UserSettingsGeneralTab extends React.Component {
@@ -208,7 +208,7 @@ export default class UserSettingsGeneralTab extends React.Component {
}
setupInitialState(props) {
var user = props.user;
- var emailEnabled = !global.window.config.ByPassEmail;
+ var emailEnabled = global.window.config.SendEmailNotifications === 'true';
return {username: user.username, firstName: user.first_name, lastName: user.last_name, nickname: user.nickname,
email: user.email, picture: null, loadingPicture: false, emailEnabled: emailEnabled};
}
diff --git a/web/react/components/user_settings/user_settings_integrations.jsx b/web/react/components/user_settings/user_settings_integrations.jsx
new file mode 100644
index 000000000..cb45c5178
--- /dev/null
+++ b/web/react/components/user_settings/user_settings_integrations.jsx
@@ -0,0 +1,95 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+var SettingItemMin = require('../setting_item_min.jsx');
+var SettingItemMax = require('../setting_item_max.jsx');
+var ManageIncomingHooks = require('./manage_incoming_hooks.jsx');
+
+export default class UserSettingsIntegrationsTab extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.updateSection = this.updateSection.bind(this);
+ this.handleClose = this.handleClose.bind(this);
+
+ this.state = {};
+ }
+ updateSection(section) {
+ this.props.updateSection(section);
+ }
+ handleClose() {
+ this.updateSection('');
+ }
+ componentDidMount() {
+ $('#user_settings').on('hidden.bs.modal', this.handleClose);
+ }
+ componentWillUnmount() {
+ $('#user_settings').off('hidden.bs.modal', this.handleClose);
+ }
+ render() {
+ let incomingHooksSection;
+ var inputs = [];
+
+ if (this.props.activeSection === 'incoming-hooks') {
+ inputs.push(
+ <ManageIncomingHooks />
+ );
+
+ incomingHooksSection = (
+ <SettingItemMax
+ title='Incoming Webhooks'
+ inputs={inputs}
+ updateSection={function clearSection(e) {
+ this.updateSection('');
+ e.preventDefault();
+ }.bind(this)}
+ />
+ );
+ } else {
+ incomingHooksSection = (
+ <SettingItemMin
+ title='Incoming Webhooks'
+ describe='Manage your incoming webhooks'
+ updateSection={function updateNameSection() {
+ this.updateSection('incoming-hooks');
+ }.bind(this)}
+ />
+ );
+ }
+
+ return (
+ <div>
+ <div className='modal-header'>
+ <button
+ type='button'
+ className='close'
+ data-dismiss='modal'
+ aria-label='Close'
+ >
+ <span aria-hidden='true'>{'×'}</span>
+ </button>
+ <h4
+ className='modal-title'
+ ref='title'
+ >
+ <i className='modal-back'></i>
+ {'Integration Settings'}
+ </h4>
+ </div>
+ <div className='user-settings'>
+ <h3 className='tab-header'>{'Integration Settings'}</h3>
+ <div className='divider-dark first'/>
+ {incomingHooksSection}
+ <div className='divider-dark'/>
+ </div>
+ </div>
+ );
+ }
+}
+
+UserSettingsIntegrationsTab.propTypes = {
+ user: React.PropTypes.object,
+ updateSection: React.PropTypes.func,
+ updateTab: React.PropTypes.func,
+ activeSection: React.PropTypes.string
+};
diff --git a/web/react/components/user_settings_modal.jsx b/web/react/components/user_settings/user_settings_modal.jsx
index 67a4d0041..5113d2429 100644
--- a/web/react/components/user_settings_modal.jsx
+++ b/web/react/components/user_settings/user_settings_modal.jsx
@@ -1,7 +1,7 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var SettingsSidebar = require('./settings_sidebar.jsx');
+var SettingsSidebar = require('../settings_sidebar.jsx');
var UserSettings = require('./user_settings.jsx');
export default class UserSettingsModal extends React.Component {
@@ -38,6 +38,9 @@ export default class UserSettingsModal extends React.Component {
if (global.window.config.EnableOAuthServiceProvider === 'true') {
tabs.push({name: 'developer', uiName: 'Developer', icon: 'glyphicon glyphicon-th'});
}
+ if (global.window.config.EnableIncomingWebhooks === 'true') {
+ tabs.push({name: 'integrations', uiName: 'Integrations', icon: 'glyphicon glyphicon-transfer'});
+ }
return (
<div
@@ -57,7 +60,7 @@ export default class UserSettingsModal extends React.Component {
data-dismiss='modal'
aria-label='Close'
>
- <span aria-hidden='true'>{'x'}</span>
+ <span aria-hidden='true'>{'×'}</span>
</button>
<h4
className='modal-title'
diff --git a/web/react/components/user_settings_notifications.jsx b/web/react/components/user_settings/user_settings_notifications.jsx
index dadbb669b..ba14f019f 100644
--- a/web/react/components/user_settings_notifications.jsx
+++ b/web/react/components/user_settings/user_settings_notifications.jsx
@@ -1,12 +1,12 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var UserStore = require('../stores/user_store.jsx');
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
-var client = require('../utils/client.jsx');
-var AsyncClient = require('../utils/async_client.jsx');
-var utils = require('../utils/utils.jsx');
+var UserStore = require('../../stores/user_store.jsx');
+var SettingItemMin = require('../setting_item_min.jsx');
+var SettingItemMax = require('../setting_item_max.jsx');
+var client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var utils = require('../../utils/utils.jsx');
var assign = require('object-assign');
function getNotificationsStateFromStores() {
@@ -241,7 +241,7 @@ export default class NotificationsTab extends React.Component {
checked={notifyActive[1]}
onChange={this.handleNotifyRadio.bind(this, 'mention')}
>
- Only for mentions and private messages
+ Only for mentions and direct messages
</input>
</label>
<br/>
@@ -265,9 +265,12 @@ export default class NotificationsTab extends React.Component {
e.preventDefault();
}.bind(this);
+ const extraInfo = <span>{'Desktop notifications are available on Firefox, Safari, and Chrome.'}</span>;
+
desktopSection = (
<SettingItemMax
title='Send desktop notifications'
+ extraInfo={extraInfo}
inputs={inputs}
submit={this.handleSubmit}
server_error={serverError}
@@ -277,7 +280,7 @@ export default class NotificationsTab extends React.Component {
} else {
let describe = '';
if (this.state.notifyLevel === 'mention') {
- describe = 'Only for mentions and private messages';
+ describe = 'Only for mentions and direct messages';
} else if (this.state.notifyLevel === 'none') {
describe = 'Never';
} else {
@@ -343,9 +346,12 @@ export default class NotificationsTab extends React.Component {
e.preventDefault();
}.bind(this);
+ const extraInfo = <span>{'Desktop notification sounds are available on Firefox, Safari, Chrome, Internet Explorer, and Edge.'}</span>;
+
soundSection = (
<SettingItemMax
title='Desktop notification sounds'
+ extraInfo={extraInfo}
inputs={inputs}
submit={this.handleSubmit}
server_error={serverError}
@@ -414,7 +420,7 @@ export default class NotificationsTab extends React.Component {
</label>
<br/>
</div>
- <div><br/>{'Email notifications are sent for mentions and private messages after you have been away from ' + global.window.config.SiteName + ' for 5 minutes.'}</div>
+ <div><br/>{'Email notifications are sent for mentions and direct messages after you have been away from ' + global.window.config.SiteName + ' for 5 minutes.'}</div>
</div>
);
diff --git a/web/react/components/user_settings_security.jsx b/web/react/components/user_settings/user_settings_security.jsx
index c10d790ae..b59c08af0 100644
--- a/web/react/components/user_settings_security.jsx
+++ b/web/react/components/user_settings/user_settings_security.jsx
@@ -1,11 +1,11 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
-var Client = require('../utils/client.jsx');
-var AsyncClient = require('../utils/async_client.jsx');
-var Constants = require('../utils/constants.jsx');
+var SettingItemMin = require('../setting_item_min.jsx');
+var SettingItemMax = require('../setting_item_max.jsx');
+var Client = require('../../utils/client.jsx');
+var AsyncClient = require('../../utils/async_client.jsx');
+var Constants = require('../../utils/constants.jsx');
export default class SecurityTab extends React.Component {
constructor(props) {
diff --git a/web/react/components/user_settings_appearance.jsx b/web/react/components/user_settings_appearance.jsx
deleted file mode 100644
index 3df013d03..000000000
--- a/web/react/components/user_settings_appearance.jsx
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
-// See License.txt for license information.
-
-var UserStore = require('../stores/user_store.jsx');
-var SettingItemMin = require('./setting_item_min.jsx');
-var SettingItemMax = require('./setting_item_max.jsx');
-var Client = require('../utils/client.jsx');
-var Utils = require('../utils/utils.jsx');
-
-var ThemeColors = ['#2389d7', '#008a17', '#dc4fad', '#ac193d', '#0072c6', '#d24726', '#ff8f32', '#82ba00', '#03b3b2', '#008299', '#4617b4', '#8c0095', '#004b8b', '#004b8b', '#570000', '#380000', '#585858', '#000000'];
-
-export default class UserSettingsAppearance extends React.Component {
- constructor(props) {
- super(props);
-
- this.submitTheme = this.submitTheme.bind(this);
- this.updateTheme = this.updateTheme.bind(this);
- this.handleClose = this.handleClose.bind(this);
-
- this.state = this.getStateFromStores();
- }
- getStateFromStores() {
- var user = UserStore.getCurrentUser();
- var theme = '#2389d7';
- if (ThemeColors != null) {
- theme = ThemeColors[0];
- }
- if (user.props && user.props.theme) {
- theme = user.props.theme;
- }
-
- return {theme: theme.toLowerCase()};
- }
- submitTheme(e) {
- e.preventDefault();
- var user = UserStore.getCurrentUser();
- if (!user.props) {
- user.props = {};
- }
- user.props.theme = this.state.theme;
-
- Client.updateUser(user,
- function success() {
- this.props.updateSection('');
- window.location.reload();
- }.bind(this),
- function fail(err) {
- var state = this.getStateFromStores();
- state.serverError = err;
- this.setState(state);
- }.bind(this)
- );
- }
- updateTheme(e) {
- var hex = Utils.rgb2hex(e.target.style.backgroundColor);
- this.setState({theme: hex.toLowerCase()});
- }
- handleClose() {
- this.setState({serverError: null});
- this.props.updateTab('general');
- }
- componentDidMount() {
- if (this.props.activeSection === 'theme') {
- $(React.findDOMNode(this.refs[this.state.theme])).addClass('active-border');
- }
- $('#user_settings').on('hidden.bs.modal', this.handleClose);
- }
- componentDidUpdate() {
- if (this.props.activeSection === 'theme') {
- $('.color-btn').removeClass('active-border');
- $(React.findDOMNode(this.refs[this.state.theme])).addClass('active-border');
- }
- }
- componentWillUnmount() {
- $('#user_settings').off('hidden.bs.modal', this.handleClose);
- this.props.updateSection('');
- }
- render() {
- var serverError;
- if (this.state.serverError) {
- serverError = this.state.serverError;
- }
-
- var themeSection;
- var self = this;
-
- if (ThemeColors != null) {
- if (this.props.activeSection === 'theme') {
- var themeButtons = [];
-
- for (var i = 0; i < ThemeColors.length; i++) {
- themeButtons.push(
- <button
- key={ThemeColors[i] + 'key' + i}
- ref={ThemeColors[i]}
- type='button'
- className='btn btn-lg color-btn'
- style={{backgroundColor: ThemeColors[i]}}
- onClick={this.updateTheme}
- />
- );
- }
-
- var inputs = [];
-
- inputs.push(
- <li
- key='themeColorSetting'
- className='setting-list-item'
- >
- <div
- className='btn-group'
- data-toggle='buttons-radio'
- >
- {themeButtons}
- </div>
- </li>
- );
-
- themeSection = (
- <SettingItemMax
- title='Theme Color'
- inputs={inputs}
- submit={this.submitTheme}
- serverError={serverError}
- updateSection={function updateSection(e) {
- self.props.updateSection('');
- e.preventDefault();
- }}
- />
- );
- } else {
- themeSection = (
- <SettingItemMin
- title='Theme Color'
- describe={this.state.theme}
- updateSection={function updateSection() {
- self.props.updateSection('theme');
- }}
- />
- );
- }
- }
-
- return (
- <div>
- <div className='modal-header'>
- <button
- type='button'
- className='close'
- data-dismiss='modal'
- aria-label='Close'
- >
- <span aria-hidden='true'>&times;</span>
- </button>
- <h4
- className='modal-title'
- ref='title'
- >
- <i className='modal-back'></i>Appearance Settings
- </h4>
- </div>
- <div className='user-settings'>
- <h3 className='tab-header'>Appearance Settings</h3>
- <div className='divider-dark first'/>
- {themeSection}
- <div className='divider-dark'/>
- </div>
- </div>
- );
- }
-}
-
-UserSettingsAppearance.defaultProps = {
- activeSection: ''
-};
-UserSettingsAppearance.propTypes = {
- activeSection: React.PropTypes.string,
- updateSection: React.PropTypes.func,
- updateTab: React.PropTypes.func
-};
diff --git a/web/react/components/view_image.jsx b/web/react/components/view_image.jsx
index f7c980396..a7fecb689 100644
--- a/web/react/components/view_image.jsx
+++ b/web/react/components/view_image.jsx
@@ -1,8 +1,11 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
-var Client = require('../utils/client.jsx');
-var Utils = require('../utils/utils.jsx');
+const Client = require('../utils/client.jsx');
+const Utils = require('../utils/utils.jsx');
+const Constants = require('../utils/constants.jsx');
+const ViewImagePopoverBar = require('./view_image_popover_bar.jsx');
+const Modal = ReactBootstrap.Modal;
export default class ViewImageModal extends React.Component {
constructor(props) {
@@ -16,6 +19,10 @@ export default class ViewImageModal extends React.Component {
this.handleKeyPress = this.handleKeyPress.bind(this);
this.getPublicLink = this.getPublicLink.bind(this);
this.getPreviewImagePath = this.getPreviewImagePath.bind(this);
+ this.onModalShown = this.onModalShown.bind(this);
+ this.onModalHidden = this.onModalHidden.bind(this);
+ this.onMouseEnterImage = this.onMouseEnterImage.bind(this);
+ this.onMouseLeaveImage = this.onMouseLeaveImage.bind(this);
var loaded = [];
var progress = [];
@@ -23,9 +30,20 @@ export default class ViewImageModal extends React.Component {
loaded.push(false);
progress.push(0);
}
- this.state = {imgId: this.props.startId, viewed: false, loaded: loaded, progress: progress, images: {}, fileSizes: {}};
+ this.state = {
+ imgId: this.props.startId,
+ imgHeight: '100%',
+ loaded: loaded,
+ progress: progress,
+ images: {},
+ fileSizes: {},
+ showFooter: false
+ };
}
- handleNext() {
+ handleNext(e) {
+ if (e) {
+ e.stopPropagation();
+ }
var id = this.state.imgId + 1;
if (id > this.props.filenames.length - 1) {
id = 0;
@@ -33,7 +51,10 @@ export default class ViewImageModal extends React.Component {
this.setState({imgId: id});
this.loadImage(id);
}
- handlePrev() {
+ handlePrev(e) {
+ if (e) {
+ e.stopPropagation();
+ }
var id = this.state.imgId - 1;
if (id < 0) {
id = this.props.filenames.length - 1;
@@ -50,15 +71,27 @@ export default class ViewImageModal extends React.Component {
this.handlePrev();
}
}
- componentWillReceiveProps(nextProps) {
+ onModalShown(nextProps) {
this.setState({imgId: nextProps.startId});
+ this.loadImage(nextProps.startId);
+ }
+ onModalHidden() {
+ if (this.refs.video) {
+ var video = React.findDOMNode(this.refs.video);
+ video.pause();
+ video.currentTime = 0;
+ }
+ }
+ componentWillReceiveProps(nextProps) {
+ if (nextProps.show === true && this.props.show === false) {
+ this.onModalShown(nextProps);
+ } else if (nextProps.show === false && this.props.show === true) {
+ this.onModalHidden();
+ }
}
loadImage(id) {
var imgHeight = $(window).height() - 100;
- if (this.state.loaded[id] || this.state.images[id]) {
- $('.modal .modal-image .image-wrapper img').css('max-height', imgHeight);
- return;
- }
+ this.setState({imgHeight});
var filename = this.props.filenames[id];
@@ -68,84 +101,27 @@ export default class ViewImageModal extends React.Component {
if (fileType === 'image') {
var img = new Image();
img.load(this.getPreviewImagePath(filename),
- function load() {
- var progress = this.state.progress;
- progress[id] = img.completedPercentage;
- this.setState({progress: progress});
- }.bind(this));
- img.onload = (function onload(imgid) {
- return function onloadReturn() {
- var loaded = this.state.loaded;
- loaded[imgid] = true;
- this.setState({loaded: loaded});
- $(React.findDOMNode(this.refs.image)).css('max-height', imgHeight);
- }.bind(this);
- }.bind(this)(id));
+ () => {
+ const progress = this.state.progress;
+ progress[id] = img.completedPercentage;
+ this.setState({progress});
+ });
+ img.onload = () => {
+ const loaded = this.state.loaded;
+ loaded[id] = true;
+ this.setState({loaded});
+ };
var images = this.state.images;
images[id] = img;
- this.setState({images: images});
+ this.setState({images});
} else {
// there's nothing to load for non-image files
var loaded = this.state.loaded;
loaded[id] = true;
- this.setState({loaded: loaded});
- }
- }
- componentDidUpdate() {
- if (this.state.loaded[this.state.imgId]) {
- if (this.refs.imageWrap) {
- $(React.findDOMNode(this.refs.imageWrap)).removeClass('default');
- }
+ this.setState({loaded});
}
}
componentDidMount() {
- $('#' + this.props.modalId).on('shown.bs.modal', function onModalShow() {
- this.setState({viewed: true});
- this.loadImage(this.state.imgId);
- }.bind(this));
-
- $('#' + this.props.modalId).on('hidden.bs.modal', function onModalHide() {
- if (this.refs.video) {
- var video = React.findDOMNode(this.refs.video);
- video.pause();
- video.currentTime = 0;
- }
- }.bind(this));
-
- $(React.findDOMNode(this.refs.modal)).click(function onModalClick(e) {
- if (e.target === this || e.target === React.findDOMNode(this.refs.imageBody)) {
- $('.image_modal').modal('hide');
- }
- }.bind(this));
-
- $(React.findDOMNode(this.refs.imageWrap)).hover(
- function onModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).addClass('footer--show');
- }.bind(this), function offModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).removeClass('footer--show');
- }.bind(this)
- );
-
- if (this.refs.previewArrowLeft) {
- $(React.findDOMNode(this.refs.previewArrowLeft)).hover(
- function onModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).addClass('footer--show');
- }.bind(this), function offModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).removeClass('footer--show');
- }.bind(this)
- );
- }
-
- if (this.refs.previewArrowRight) {
- $(React.findDOMNode(this.refs.previewArrowRight)).hover(
- function onModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).addClass('footer--show');
- }.bind(this), function offModalHover() {
- $(React.findDOMNode(this.refs.imageFooter)).removeClass('footer--show');
- }.bind(this)
- );
- }
-
$(window).on('keyup', this.handleKeyPress);
// keep track of whether or not this component is mounted so we can safely set the state asynchronously
@@ -189,6 +165,12 @@ export default class ViewImageModal extends React.Component {
// only images have proper previews, so just use a placeholder icon for non-images
return Utils.getPreviewImagePathForFileType(fileType);
}
+ onMouseEnterImage() {
+ this.setState({showFooter: true});
+ }
+ onMouseLeaveImage() {
+ this.setState({showFooter: false});
+ }
render() {
if (this.props.filenames.length < 1 || this.props.filenames.length - 1 < this.state.imgId) {
return <div/>;
@@ -219,11 +201,20 @@ export default class ViewImageModal extends React.Component {
</a>
);
} else if (fileType === 'video' || fileType === 'audio') {
+ let width = Constants.WEB_VIDEO_WIDTH;
+ let height = Constants.WEB_VIDEO_HEIGHT;
+ if (Utils.isMobile()) {
+ width = Constants.MOBILE_VIDEO_WIDTH;
+ height = Constants.MOBILE_VIDEO_HEIGHT;
+ }
+
content = (
<video
ref='video'
data-setup='{}'
controls='controls'
+ width={width}
+ height={height}
>
<source src={Utils.getWindowLocationOrigin() + '/api/v1/files/get' + filename} />
</video>
@@ -299,23 +290,6 @@ export default class ViewImageModal extends React.Component {
bgClass = 'black-bg';
}
- var publicLink = '';
- if (global.window.config.AllowPublicLink) {
- publicLink = (
- <div>
- <a
- href='#'
- className='public-link text'
- data-title='Public Image'
- onClick={this.getPublicLink}
- >
- Get Public Link
- </a>
- <span className='text'> | </span>
- </div>
- );
- }
-
var leftArrow = '';
var rightArrow = '';
if (this.props.filenames.length > 1) {
@@ -342,65 +316,61 @@ export default class ViewImageModal extends React.Component {
);
}
+ let closeButtonClass = 'modal-close';
+ if (this.state.showFooter) {
+ closeButtonClass += ' modal-close--show';
+ }
+
return (
- <div
- className='modal fade image_modal'
- ref='modal'
- id={this.props.modalId}
- tabIndex='-1'
- role='dialog'
- aria-hidden='true'
+ <Modal
+ show={this.props.show}
+ onHide={this.props.onModalDismissed}
+ className='image_modal'
+ dialogClassName='modal-image'
>
- <div className='modal-dialog modal-image'>
- <div className='modal-content image-content'>
+ <Modal.Body
+ modalClassName='image-body'
+ onClick={this.props.onModalDismissed}
+ >
+ <div
+ className={'image-wrapper ' + bgClass}
+ style={{maxHeight: this.state.imgHeight}}
+ onMouseEnter={this.onMouseEnterImage}
+ onMouseLeave={this.onMouseLeaveImage}
+ onClick={(e) => e.stopPropagation()}
+ >
<div
- ref='imageBody'
- className='modal-body image-body'
- >
- <div
- ref='imageWrap'
- className={'image-wrapper default ' + bgClass}
- >
- <div
- className='modal-close'
- data-dismiss='modal'
- />
- {content}
- <div
- ref='imageFooter'
- className='modal-button-bar'
- >
- <span className='pull-left text'>{'File ' + (this.state.imgId + 1) + ' of ' + this.props.filenames.length}</span>
- <div className='image-links'>
- {publicLink}
- <a
- href={fileUrl}
- download={name}
- className='text'
- >
- Download
- </a>
- </div>
- </div>
- </div>
- {leftArrow}
- {rightArrow}
- </div>
+ className={closeButtonClass}
+ onClick={this.props.onModalDismissed}
+ />
+ {content}
+ <ViewImagePopoverBar
+ show={this.state.showFooter}
+ fileId={this.state.imgId}
+ totalFiles={this.props.filenames.length}
+ filename={name}
+ fileURL={fileUrl}
+ onGetPublicLinkPressed={this.getPublicLink}
+ />
</div>
- </div>
- </div>
+ {leftArrow}
+ {rightArrow}
+ </Modal.Body>
+ </Modal>
);
}
}
ViewImageModal.defaultProps = {
+ show: false,
filenames: [],
- modalId: '',
channelId: '',
userId: '',
startId: 0
};
ViewImageModal.propTypes = {
+ show: React.PropTypes.bool.isRequired,
+ onModalDismissed: React.PropTypes.func.isRequired,
filenames: React.PropTypes.array,
modalId: React.PropTypes.string,
channelId: React.PropTypes.string,
diff --git a/web/react/components/view_image_popover_bar.jsx b/web/react/components/view_image_popover_bar.jsx
new file mode 100644
index 000000000..68817d751
--- /dev/null
+++ b/web/react/components/view_image_popover_bar.jsx
@@ -0,0 +1,66 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+export default class ViewImagePopoverBar extends React.Component {
+ constructor(props) {
+ super(props);
+ }
+ render() {
+ var publicLink = '';
+ if (global.window.config.EnablePublicLink === 'true') {
+ publicLink = (
+ <div>
+ <a
+ href='#'
+ className='public-link text'
+ data-title='Public Image'
+ onClick={this.getPublicLink}
+ >
+ {'Get Public Link'}
+ </a>
+ <span className='text'>{' | '}</span>
+ </div>
+ );
+ }
+
+ var footerClass = 'modal-button-bar';
+ if (this.props.show) {
+ footerClass += ' footer--show';
+ }
+
+ return (
+ <div
+ ref='imageFooter'
+ className={footerClass}
+ >
+ <span className='pull-left text'>{'File ' + (this.props.fileId + 1) + ' of ' + this.props.totalFiles}</span>
+ <div className='image-links'>
+ {publicLink}
+ <a
+ href={this.props.fileURL}
+ download={this.props.filename}
+ className='text'
+ >
+ {'Download'}
+ </a>
+ </div>
+ </div>
+ );
+ }
+}
+ViewImagePopoverBar.defaultProps = {
+ show: false,
+ imgId: 0,
+ totalFiles: 0,
+ filename: '',
+ fileURL: ''
+};
+
+ViewImagePopoverBar.propTypes = {
+ show: React.PropTypes.bool.isRequired,
+ fileId: React.PropTypes.number.isRequired,
+ totalFiles: React.PropTypes.number.isRequired,
+ filename: React.PropTypes.string.isRequired,
+ fileURL: React.PropTypes.string.isRequired,
+ onGetPublicLinkPressed: React.PropTypes.func.isRequired
+};
diff --git a/web/react/package.json b/web/react/package.json
index dd7d45f8a..a9eba6c6c 100644
--- a/web/react/package.json
+++ b/web/react/package.json
@@ -4,13 +4,14 @@
"private": true,
"dependencies": {
"autolinker": "0.18.1",
+ "babel-runtime": "5.8.24",
+ "bootstrap-colorpicker": "2.2.0",
"flux": "2.1.1",
"keymirror": "0.1.1",
+ "marked": "0.3.5",
"object-assign": "3.0.0",
"react-zeroclipboard-mixin": "0.1.0",
- "twemoji": "1.4.1",
- "babel-runtime": "5.8.24",
- "marked": "0.3.5"
+ "twemoji": "1.4.1"
},
"devDependencies": {
"browserify": "11.0.1",
@@ -28,8 +29,15 @@
},
"browserify": {
"transform": [
- ["babelify", { "optional": ["runtime"] }],
- "envify"
+ [
+ "babelify",
+ {
+ "optional": [
+ "runtime"
+ ]
+ }
+ ],
+ "envify"
]
},
"jest": {
diff --git a/web/react/pages/channel.jsx b/web/react/pages/channel.jsx
index 43493de45..74259194a 100644
--- a/web/react/pages/channel.jsx
+++ b/web/react/pages/channel.jsx
@@ -19,13 +19,14 @@ var DeletePostModal = require('../components/delete_post_modal.jsx');
var MoreChannelsModal = require('../components/more_channels.jsx');
var PostDeletedModal = require('../components/post_deleted_modal.jsx');
var ChannelNotificationsModal = require('../components/channel_notifications.jsx');
-var UserSettingsModal = require('../components/user_settings_modal.jsx');
+var UserSettingsModal = require('../components/user_settings/user_settings_modal.jsx');
var TeamSettingsModal = require('../components/team_settings_modal.jsx');
var ChannelMembersModal = require('../components/channel_members.jsx');
var ChannelInviteModal = require('../components/channel_invite_modal.jsx');
var TeamMembersModal = require('../components/team_members.jsx');
var DirectChannelModal = require('../components/more_direct_channels.jsx');
var ErrorBar = require('../components/error_bar.jsx');
+var ErrorStore = require('../stores/error_store.jsx');
var ChannelLoader = require('../components/channel_loader.jsx');
var MentionList = require('../components/mention_list.jsx');
var ChannelInfoModal = require('../components/channel_info_modal.jsx');
@@ -34,6 +35,7 @@ var ActivityLogModal = require('../components/activity_log_modal.jsx');
var RemovedFromChannelModal = require('../components/removed_from_channel_modal.jsx');
var FileUploadOverlay = require('../components/file_upload_overlay.jsx');
var RegisterAppModal = require('../components/register_app_modal.jsx');
+var ImportThemeModal = require('../components/user_settings/import_theme_modal.jsx');
var Constants = require('../utils/constants.jsx');
var ActionTypes = Constants.ActionTypes;
@@ -85,6 +87,11 @@ function setupChannelPage(props) {
);
React.render(
+ <ImportThemeModal />,
+ document.getElementById('import_theme_modal')
+ );
+
+ React.render(
<TeamSettingsModal teamDisplayName={props.TeamDisplayName} />,
document.getElementById('team_settings_modal')
);
@@ -228,6 +235,11 @@ function setupChannelPage(props) {
<RegisterAppModal />,
document.getElementById('register_app_modal')
);
+
+ if (global.window.config.SendEmailNotifications === 'false') {
+ ErrorStore.storeLastError({message: 'Preview Mode: Email notifications have not been configured'});
+ ErrorStore.emitChange();
+ }
}
global.window.setup_channel_page = setupChannelPage;
diff --git a/web/react/pages/login.jsx b/web/react/pages/login.jsx
index 830f622fa..f78e0f37a 100644
--- a/web/react/pages/login.jsx
+++ b/web/react/pages/login.jsx
@@ -8,7 +8,6 @@ function setupLoginPage(props) {
<Login
teamDisplayName={props.TeamDisplayName}
teamName={props.TeamName}
- authServices={props.AuthServices}
/>,
document.getElementById('login')
);
diff --git a/web/react/pages/signup_team.jsx b/web/react/pages/signup_team.jsx
index 427daf577..d0e08f446 100644
--- a/web/react/pages/signup_team.jsx
+++ b/web/react/pages/signup_team.jsx
@@ -3,11 +3,9 @@
var SignupTeam = require('../components/signup_team.jsx');
-function setupSignupTeamPage(props) {
- var services = JSON.parse(props.AuthServices);
-
+function setupSignupTeamPage() {
React.render(
- <SignupTeam services={services} />,
+ <SignupTeam />,
document.getElementById('signup-team')
);
}
diff --git a/web/react/pages/signup_user_complete.jsx b/web/react/pages/signup_user_complete.jsx
index 112aaa3f2..cc7607187 100644
--- a/web/react/pages/signup_user_complete.jsx
+++ b/web/react/pages/signup_user_complete.jsx
@@ -12,7 +12,6 @@ function setupSignupUserCompletePage(props) {
email={props.Email}
hash={props.Hash}
data={props.Data}
- authServices={props.AuthServices}
/>,
document.getElementById('signup-user-complete')
);
diff --git a/web/react/pages/verify.jsx b/web/react/pages/verify.jsx
index e48471bbd..16a9846e5 100644
--- a/web/react/pages/verify.jsx
+++ b/web/react/pages/verify.jsx
@@ -9,6 +9,7 @@ global.window.setupVerifyPage = function setupVerifyPage(props) {
isVerified={props.IsVerified}
teamURL={props.TeamURL}
userEmail={props.UserEmail}
+ resendSuccess={props.ResendSuccess}
/>,
document.getElementById('verify')
);
diff --git a/web/react/stores/admin_store.jsx b/web/react/stores/admin_store.jsx
index dd5b60a24..7b2aeb631 100644
--- a/web/react/stores/admin_store.jsx
+++ b/web/react/stores/admin_store.jsx
@@ -4,11 +4,14 @@
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var EventEmitter = require('events').EventEmitter;
+var BrowserStore = require('../stores/browser_store.jsx');
+
var Constants = require('../utils/constants.jsx');
var ActionTypes = Constants.ActionTypes;
var LOG_CHANGE_EVENT = 'log_change';
var CONFIG_CHANGE_EVENT = 'config_change';
+var ALL_TEAMS_EVENT = 'all_team_change';
class AdminStoreClass extends EventEmitter {
constructor() {
@@ -16,6 +19,7 @@ class AdminStoreClass extends EventEmitter {
this.logs = null;
this.config = null;
+ this.teams = null;
this.emitLogChange = this.emitLogChange.bind(this);
this.addLogChangeListener = this.addLogChangeListener.bind(this);
@@ -24,6 +28,10 @@ class AdminStoreClass extends EventEmitter {
this.emitConfigChange = this.emitConfigChange.bind(this);
this.addConfigChangeListener = this.addConfigChangeListener.bind(this);
this.removeConfigChangeListener = this.removeConfigChangeListener.bind(this);
+
+ this.emitAllTeamsChange = this.emitAllTeamsChange.bind(this);
+ this.addAllTeamsChangeListener = this.addAllTeamsChangeListener.bind(this);
+ this.removeAllTeamsChangeListener = this.removeAllTeamsChangeListener.bind(this);
}
emitLogChange() {
@@ -50,6 +58,18 @@ class AdminStoreClass extends EventEmitter {
this.removeListener(CONFIG_CHANGE_EVENT, callback);
}
+ emitAllTeamsChange() {
+ this.emit(ALL_TEAMS_EVENT);
+ }
+
+ addAllTeamsChangeListener(callback) {
+ this.on(ALL_TEAMS_EVENT, callback);
+ }
+
+ removeAllTeamsChangeListener(callback) {
+ this.removeListener(ALL_TEAMS_EVENT, callback);
+ }
+
getLogs() {
return this.logs;
}
@@ -65,6 +85,22 @@ class AdminStoreClass extends EventEmitter {
saveConfig(config) {
this.config = config;
}
+
+ getAllTeams() {
+ return this.teams;
+ }
+
+ saveAllTeams(teams) {
+ this.teams = teams;
+ }
+
+ getSelectedTeams() {
+ return BrowserStore.getItem('seleted_teams');
+ }
+
+ saveSelectedTeams(teams) {
+ BrowserStore.setItem('seleted_teams', teams);
+ }
}
var AdminStore = new AdminStoreClass();
@@ -81,6 +117,10 @@ AdminStoreClass.dispatchToken = AppDispatcher.register((payload) => {
AdminStore.saveConfig(action.config);
AdminStore.emitConfigChange();
break;
+ case ActionTypes.RECIEVED_ALL_TEAMS:
+ AdminStore.saveAllTeams(action.teams);
+ AdminStore.emitAllTeamsChange();
+ break;
default:
}
});
diff --git a/web/react/stores/error_store.jsx b/web/react/stores/error_store.jsx
index 597c88cff..ece7d8522 100644
--- a/web/react/stores/error_store.jsx
+++ b/web/react/stores/error_store.jsx
@@ -48,7 +48,7 @@ class ErrorStoreClass extends EventEmitter {
var ErrorStore = new ErrorStoreClass();
-ErrorStore.dispatchToken = AppDispatcher.register(function registry(payload) {
+ErrorStore.dispatchToken = AppDispatcher.register((payload) => {
var action = payload.action;
switch (action.type) {
case ActionTypes.RECIEVED_ERROR:
diff --git a/web/react/stores/socket_store.jsx b/web/react/stores/socket_store.jsx
index ae74059d1..1d853f979 100644
--- a/web/react/stores/socket_store.jsx
+++ b/web/react/stores/socket_store.jsx
@@ -3,6 +3,7 @@
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var UserStore = require('./user_store.jsx');
+var ErrorStore = require('./error_store.jsx');
var EventEmitter = require('events').EventEmitter;
var Constants = require('../utils/constants.jsx');
@@ -21,6 +22,7 @@ class SocketStoreClass extends EventEmitter {
this.addChangeListener = this.addChangeListener.bind(this);
this.removeChangeListener = this.removeChangeListener.bind(this);
this.sendMessage = this.sendMessage.bind(this);
+ this.failCount = 0;
this.initialize();
}
@@ -37,27 +39,43 @@ class SocketStoreClass extends EventEmitter {
protocol = 'wss://';
}
var connUrl = protocol + location.host + '/api/v1/websocket';
- console.log('connecting to ' + connUrl); //eslint-disable-line no-console
+ if (this.failCount === 0) {
+ console.log('websocket connecting to ' + connUrl); //eslint-disable-line no-console
+ }
conn = new WebSocket(connUrl);
- conn.onclose = function closeConn(evt) {
- console.log('websocket closed'); //eslint-disable-line no-console
- console.log(evt); //eslint-disable-line no-console
+ conn.onopen = () => {
+ if (this.failCount > 0) {
+ console.log('websocket re-established connection'); //eslint-disable-line no-console
+ }
+
+ this.failCount = 0;
+ ErrorStore.storeLastError(null);
+ ErrorStore.emitChange();
+ };
+
+ conn.onclose = () => {
conn = null;
setTimeout(
- function reconnect() {
+ () => {
this.initialize();
- }.bind(this),
+ },
3000
);
- }.bind(this);
+ };
+
+ conn.onerror = (evt) => {
+ if (this.failCount === 0) {
+ console.log('websocket error ' + evt); //eslint-disable-line no-console
+ }
+
+ this.failCount = this.failCount + 1;
- conn.onerror = function connError(evt) {
- console.log('websocket error'); //eslint-disable-line no-console
- console.log(evt); //eslint-disable-line no-console
+ ErrorStore.storeLastError({connErrorCount: this.failCount, message: 'We cannot reach the Mattermost service. The service may be down or misconfigured. Please contact an administrator to make sure the WebSocket port is configured properly.'});
+ ErrorStore.emitChange();
};
- conn.onmessage = function connMessage(evt) {
+ conn.onmessage = (evt) => {
AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_MSG,
msg: JSON.parse(evt.data)
@@ -86,7 +104,7 @@ class SocketStoreClass extends EventEmitter {
var SocketStore = new SocketStoreClass();
-SocketStore.dispatchToken = AppDispatcher.register(function registry(payload) {
+SocketStore.dispatchToken = AppDispatcher.register((payload) => {
var action = payload.action;
switch (action.type) {
diff --git a/web/react/stores/user_store.jsx b/web/react/stores/user_store.jsx
index f75c1d4c3..8842263fa 100644
--- a/web/react/stores/user_store.jsx
+++ b/web/react/stores/user_store.jsx
@@ -14,6 +14,7 @@ var CHANGE_EVENT_SESSIONS = 'change_sessions';
var CHANGE_EVENT_AUDITS = 'change_audits';
var CHANGE_EVENT_TEAMS = 'change_teams';
var CHANGE_EVENT_STATUSES = 'change_statuses';
+var TOGGLE_IMPORT_MODAL_EVENT = 'toggle_import_modal';
class UserStoreClass extends EventEmitter {
constructor() {
@@ -34,6 +35,9 @@ class UserStoreClass extends EventEmitter {
this.emitStatusesChange = this.emitStatusesChange.bind(this);
this.addStatusesChangeListener = this.addStatusesChangeListener.bind(this);
this.removeStatusesChangeListener = this.removeStatusesChangeListener.bind(this);
+ this.emitToggleImportModal = this.emitToggleImportModal.bind(this);
+ this.addImportModalListener = this.addImportModalListener.bind(this);
+ this.removeImportModalListener = this.removeImportModalListener.bind(this);
this.setCurrentId = this.setCurrentId.bind(this);
this.getCurrentId = this.getCurrentId.bind(this);
this.getCurrentUser = this.getCurrentUser.bind(this);
@@ -114,6 +118,15 @@ class UserStoreClass extends EventEmitter {
removeStatusesChangeListener(callback) {
this.removeListener(CHANGE_EVENT_STATUSES, callback);
}
+ emitToggleImportModal(value) {
+ this.emit(TOGGLE_IMPORT_MODAL_EVENT, value);
+ }
+ addImportModalListener(callback) {
+ this.on(TOGGLE_IMPORT_MODAL_EVENT, callback);
+ }
+ removeImportModalListener(callback) {
+ this.removeListener(TOGGLE_IMPORT_MODAL_EVENT, callback);
+ }
setCurrentId(id) {
this.gCurrentId = id;
if (id == null) {
@@ -321,6 +334,9 @@ UserStore.dispatchToken = AppDispatcher.register(function registry(payload) {
UserStore.pSetStatuses(action.statuses);
UserStore.emitStatusesChange();
break;
+ case ActionTypes.TOGGLE_IMPORT_THEME_MODAL:
+ UserStore.emitToggleImportModal(action.value);
+ break;
default:
}
diff --git a/web/react/utils/async_client.jsx b/web/react/utils/async_client.jsx
index ed228f6c4..ab2965000 100644
--- a/web/react/utils/async_client.jsx
+++ b/web/react/utils/async_client.jsx
@@ -371,6 +371,32 @@ export function getConfig() {
);
}
+export function getAllTeams() {
+ if (isCallInProgress('getAllTeams')) {
+ return;
+ }
+
+ callTracker.getAllTeams = utils.getTimestamp();
+ client.getAllTeams(
+ (data, textStatus, xhr) => {
+ callTracker.getAllTeams = 0;
+
+ if (xhr.status === 304 || !data) {
+ return;
+ }
+
+ AppDispatcher.handleServerAction({
+ type: ActionTypes.RECIEVED_ALL_TEAMS,
+ teams: data
+ });
+ },
+ (err) => {
+ callTracker.getAllTeams = 0;
+ dispatchError(err, 'getAllTeams');
+ }
+ );
+}
+
export function findTeams(email) {
if (isCallInProgress('findTeams_' + email)) {
return;
diff --git a/web/react/utils/client.jsx b/web/react/utils/client.jsx
index c9eb09c00..715e26197 100644
--- a/web/react/utils/client.jsx
+++ b/web/react/utils/client.jsx
@@ -4,12 +4,10 @@ var BrowserStore = require('../stores/browser_store.jsx');
var TeamStore = require('../stores/team_store.jsx');
export function track(category, action, label, prop, val) {
- global.window.snowplow('trackStructEvent', category, action, label, prop, val);
global.window.analytics.track(action, {category: category, label: label, property: prop, value: val});
}
export function trackPage() {
- global.window.snowplow('trackPageView');
global.window.analytics.page();
}
@@ -29,7 +27,7 @@ function handleError(methodName, xhr, status, err) {
msg = 'error in ' + methodName + ' status=' + status + ' statusCode=' + xhr.status + ' err=' + err;
if (xhr.status === 0) {
- e = {message: 'There appears to be a problem with your internet connection'};
+ e = {message: 'There appears to be a problem with your internet connection', connErrorCount: 1};
} else {
e = {message: 'We received an unexpected status code from the server (' + xhr.status + ')'};
}
@@ -59,7 +57,7 @@ export function createTeamFromSignup(teamSignup, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(teamSignup),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createTeamFromSignup', xhr, status, err);
error(e);
@@ -74,7 +72,7 @@ export function createTeamWithSSO(team, service, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(team),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createTeamWithSSO', xhr, status, err);
error(e);
@@ -89,7 +87,7 @@ export function createUser(user, data, emailHash, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(user),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createUser', xhr, status, err);
error(e);
@@ -106,7 +104,7 @@ export function updateUser(user, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(user),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateUser', xhr, status, err);
error(e);
@@ -123,7 +121,7 @@ export function updatePassword(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('newPassword', xhr, status, err);
error(e);
@@ -140,7 +138,7 @@ export function updateUserNotifyProps(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateUserNotifyProps', xhr, status, err);
error(e);
@@ -155,7 +153,7 @@ export function updateRoles(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateRoles', xhr, status, err);
error(e);
@@ -176,7 +174,7 @@ export function updateActive(userId, active, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateActive', xhr, status, err);
error(e);
@@ -193,7 +191,7 @@ export function sendPasswordReset(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('sendPasswordReset', xhr, status, err);
error(e);
@@ -210,7 +208,7 @@ export function resetPassword(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('resetPassword', xhr, status, err);
error(e);
@@ -254,7 +252,7 @@ export function revokeSession(altId, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({id: altId}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('revokeSession', xhr, status, err);
error(e);
@@ -269,7 +267,7 @@ export function getSessions(userId, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getSessions', xhr, status, err);
error(e);
@@ -283,7 +281,7 @@ export function getAudits(userId, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getAudits', xhr, status, err);
error(e);
@@ -334,6 +332,35 @@ export function saveConfig(config, success, error) {
});
}
+export function testEmail(config, success, error) {
+ $.ajax({
+ url: '/api/v1/admin/test_email',
+ dataType: 'json',
+ contentType: 'application/json',
+ type: 'POST',
+ data: JSON.stringify(config),
+ success,
+ error: function onError(xhr, status, err) {
+ var e = handleError('testEmail', xhr, status, err);
+ error(e);
+ }
+ });
+}
+
+export function getAllTeams(success, error) {
+ $.ajax({
+ url: '/api/v1/teams/all',
+ dataType: 'json',
+ contentType: 'application/json',
+ type: 'GET',
+ success,
+ error: function onError(xhr, status, err) {
+ var e = handleError('getAllTeams', xhr, status, err);
+ error(e);
+ }
+ });
+}
+
export function getMeSynchronous(success, error) {
var currentUser = null;
$.ajax({
@@ -367,7 +394,7 @@ export function inviteMembers(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('inviteMembers', xhr, status, err);
error(e);
@@ -384,7 +411,7 @@ export function updateTeamDisplayName(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateTeamDisplayName', xhr, status, err);
error(e);
@@ -401,7 +428,7 @@ export function signupTeam(email, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({email: email}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('singupTeam', xhr, status, err);
error(e);
@@ -418,7 +445,7 @@ export function createTeam(team, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(team),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createTeam', xhr, status, err);
error(e);
@@ -433,7 +460,7 @@ export function findTeamByName(teamName, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({name: teamName}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('findTeamByName', xhr, status, err);
error(e);
@@ -448,7 +475,7 @@ export function findTeamsSendEmail(email, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({email: email}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('findTeamsSendEmail', xhr, status, err);
error(e);
@@ -465,7 +492,7 @@ export function findTeams(email, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({email: email}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('findTeams', xhr, status, err);
error(e);
@@ -480,7 +507,7 @@ export function createChannel(channel, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(channel),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createChannel', xhr, status, err);
error(e);
@@ -497,7 +524,7 @@ export function createDirectChannel(channel, userId, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({user_id: userId}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createDirectChannel', xhr, status, err);
error(e);
@@ -514,7 +541,7 @@ export function updateChannel(channel, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(channel),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateChannel', xhr, status, err);
error(e);
@@ -531,7 +558,7 @@ export function updateChannelDesc(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateChannelDesc', xhr, status, err);
error(e);
@@ -548,7 +575,7 @@ export function updateNotifyLevel(data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateNotifyLevel', xhr, status, err);
error(e);
@@ -562,7 +589,7 @@ export function joinChannel(id, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'POST',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('joinChannel', xhr, status, err);
error(e);
@@ -578,7 +605,7 @@ export function leaveChannel(id, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'POST',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('leaveChannel', xhr, status, err);
error(e);
@@ -594,7 +621,7 @@ export function deleteChannel(id, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'POST',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('deleteChannel', xhr, status, err);
error(e);
@@ -610,7 +637,7 @@ export function updateLastViewedAt(channelId, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'POST',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updateLastViewedAt', xhr, status, err);
error(e);
@@ -624,7 +651,7 @@ export function getChannels(success, error) {
url: '/api/v1/channels/',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
ifModified: true,
error: function onError(xhr, status, err) {
var e = handleError('getChannels', xhr, status, err);
@@ -639,7 +666,7 @@ export function getChannel(id, success, error) {
url: '/api/v1/channels/' + id + '/',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getChannel', xhr, status, err);
error(e);
@@ -654,7 +681,7 @@ export function getMoreChannels(success, error) {
url: '/api/v1/channels/more',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
ifModified: true,
error: function onError(xhr, status, err) {
var e = handleError('getMoreChannels', xhr, status, err);
@@ -669,7 +696,7 @@ export function getChannelCounts(success, error) {
url: '/api/v1/channels/counts',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
ifModified: true,
error: function onError(xhr, status, err) {
var e = handleError('getChannelCounts', xhr, status, err);
@@ -683,7 +710,7 @@ export function getChannelExtraInfo(id, success, error) {
url: '/api/v1/channels/' + id + '/extra_info',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getChannelExtraInfo', xhr, status, err);
error(e);
@@ -698,7 +725,7 @@ export function executeCommand(channelId, command, suggest, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({channelId: channelId, command: command, suggest: '' + suggest}),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('executeCommand', xhr, status, err);
error(e);
@@ -713,7 +740,7 @@ export function getPostsPage(channelId, offset, limit, success, error, complete)
dataType: 'json',
type: 'GET',
ifModified: true,
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getPosts', xhr, status, err);
error(e);
@@ -728,7 +755,7 @@ export function getPosts(channelId, since, success, error, complete) {
dataType: 'json',
type: 'GET',
ifModified: true,
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getPosts', xhr, status, err);
error(e);
@@ -744,7 +771,7 @@ export function getPost(channelId, postId, success, error) {
dataType: 'json',
type: 'GET',
ifModified: false,
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getPost', xhr, status, err);
error(e);
@@ -758,7 +785,7 @@ export function search(terms, success, error) {
dataType: 'json',
type: 'GET',
data: {terms: terms},
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('search', xhr, status, err);
error(e);
@@ -774,7 +801,7 @@ export function deletePost(channelId, id, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'POST',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('deletePost', xhr, status, err);
error(e);
@@ -791,7 +818,7 @@ export function createPost(post, channel, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(post),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('createPost', xhr, status, err);
error(e);
@@ -817,7 +844,7 @@ export function updatePost(post, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(post),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('updatePost', xhr, status, err);
error(e);
@@ -834,7 +861,7 @@ export function addChannelMember(id, data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('addChannelMember', xhr, status, err);
error(e);
@@ -851,7 +878,7 @@ export function removeChannelMember(id, data, success, error) {
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('removeChannelMember', xhr, status, err);
error(e);
@@ -868,7 +895,7 @@ export function getProfiles(success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
ifModified: true,
error: function onError(xhr, status, err) {
var e = handleError('getProfiles', xhr, status, err);
@@ -877,6 +904,21 @@ export function getProfiles(success, error) {
});
}
+export function getProfilesForTeam(teamId, success, error) {
+ $.ajax({
+ cache: false,
+ url: '/api/v1/users/profiles/' + teamId,
+ dataType: 'json',
+ contentType: 'application/json',
+ type: 'GET',
+ success,
+ error: function onError(xhr, status, err) {
+ var e = handleError('getProfilesForTeam', xhr, status, err);
+ error(e);
+ }
+ });
+}
+
export function uploadFile(formData, success, error) {
var request = $.ajax({
url: '/api/v1/files/upload',
@@ -885,7 +927,7 @@ export function uploadFile(formData, success, error) {
cache: false,
contentType: false,
processData: false,
- success: success,
+ success,
error: function onError(xhr, status, err) {
if (err !== 'abort') {
var e = handleError('uploadFile', xhr, status, err);
@@ -905,7 +947,7 @@ export function getFileInfo(filename, success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getFileInfo', xhr, status, err);
error(e);
@@ -919,7 +961,7 @@ export function getPublicLink(data, success, error) {
dataType: 'json',
type: 'POST',
data: JSON.stringify(data),
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getPublicLink', xhr, status, err);
error(e);
@@ -935,7 +977,7 @@ export function uploadProfileImage(imageData, success, error) {
cache: false,
contentType: false,
processData: false,
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('uploadProfileImage', xhr, status, err);
error(e);
@@ -951,7 +993,7 @@ export function importSlack(fileData, success, error) {
cache: false,
contentType: false,
processData: false,
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('importTeam', xhr, status, err);
error(e);
@@ -964,7 +1006,7 @@ export function exportTeam(success, error) {
url: '/api/v1/teams/export_team',
type: 'GET',
dataType: 'json',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('exportTeam', xhr, status, err);
error(e);
@@ -978,7 +1020,7 @@ export function getStatuses(success, error) {
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
error: function onError(xhr, status, err) {
var e = handleError('getStatuses', xhr, status, err);
error(e);
@@ -991,7 +1033,7 @@ export function getMyTeam(success, error) {
url: '/api/v1/teams/me',
dataType: 'json',
type: 'GET',
- success: success,
+ success,
ifModified: true,
error: function onError(xhr, status, err) {
var e = handleError('getMyTeam', xhr, status, err);
@@ -1000,23 +1042,6 @@ export function getMyTeam(success, error) {
});
}
-export function updateValetFeature(data, success, error) {
- $.ajax({
- url: '/api/v1/teams/update_valet_feature',
- dataType: 'json',
- contentType: 'application/json',
- type: 'POST',
- data: JSON.stringify(data),
- success: success,
- error: function onError(xhr, status, err) {
- var e = handleError('updateValetFeature', xhr, status, err);
- error(e);
- }
- });
-
- track('api', 'api_teams_update_valet_feature');
-}
-
export function registerOAuthApp(app, success, error) {
$.ajax({
url: '/api/v1/oauth/register',
@@ -1040,7 +1065,7 @@ export function allowOAuth2(responseType, clientId, redirectUri, state, scope, s
dataType: 'json',
contentType: 'application/json',
type: 'GET',
- success: success,
+ success,
error: (xhr, status, err) => {
const e = handleError('allowOAuth2', xhr, status, err);
error(e);
@@ -1049,3 +1074,46 @@ export function allowOAuth2(responseType, clientId, redirectUri, state, scope, s
module.exports.track('api', 'api_users_allow_oauth2');
}
+
+export function addIncomingHook(hook, success, error) {
+ $.ajax({
+ url: '/api/v1/hooks/incoming/create',
+ dataType: 'json',
+ contentType: 'application/json',
+ type: 'POST',
+ data: JSON.stringify(hook),
+ success,
+ error: (xhr, status, err) => {
+ var e = handleError('addIncomingHook', xhr, status, err);
+ error(e);
+ }
+ });
+}
+
+export function deleteIncomingHook(data, success, error) {
+ $.ajax({
+ url: '/api/v1/hooks/incoming/delete',
+ dataType: 'json',
+ contentType: 'application/json',
+ type: 'POST',
+ data: JSON.stringify(data),
+ success,
+ error: (xhr, status, err) => {
+ var e = handleError('deleteIncomingHook', xhr, status, err);
+ error(e);
+ }
+ });
+}
+
+export function listIncomingHooks(success, error) {
+ $.ajax({
+ url: '/api/v1/hooks/incoming/list',
+ dataType: 'json',
+ type: 'GET',
+ success,
+ error: (xhr, status, err) => {
+ var e = handleError('listIncomingHooks', xhr, status, err);
+ error(e);
+ }
+ });
+}
diff --git a/web/react/utils/constants.jsx b/web/react/utils/constants.jsx
index 03e4635b5..75e80bc7e 100644
--- a/web/react/utils/constants.jsx
+++ b/web/react/utils/constants.jsx
@@ -35,8 +35,10 @@ module.exports = {
RECIEVED_TEAM: null,
RECIEVED_CONFIG: null,
+ RECIEVED_LOGS: null,
+ RECIEVED_ALL_TEAMS: null,
- RECIEVED_LOGS: null
+ TOGGLE_IMPORT_THEME_MODAL: null
}),
PayloadSources: keyMirror({
@@ -70,6 +72,10 @@ module.exports = {
MAX_FILE_SIZE: 50000000, // 50 MB
THUMBNAIL_WIDTH: 128,
THUMBNAIL_HEIGHT: 100,
+ WEB_VIDEO_WIDTH: 640,
+ WEB_VIDEO_HEIGHT: 480,
+ MOBILE_VIDEO_WIDTH: 480,
+ MOBILE_VIDEO_HEIGHT: 360,
DEFAULT_CHANNEL: 'town-square',
OFFTOPIC_CHANNEL: 'off-topic',
GITLAB_SERVICE: 'gitlab',
@@ -110,5 +116,166 @@ module.exports = {
ONLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path class='online--icon' d='M6,5.487c1.371,0,2.482-1.116,2.482-2.493c0-1.378-1.111-2.495-2.482-2.495S3.518,1.616,3.518,2.994C3.518,4.371,4.629,5.487,6,5.487z M10.452,8.545c-0.101-0.829-0.36-1.968-0.726-2.541C9.475,5.606,8.5,5.5,8.5,5.5S8.43,7.521,6,7.521C3.507,7.521,3.5,5.5,3.5,5.5S2.527,5.606,2.273,6.004C1.908,6.577,1.648,7.716,1.547,8.545C1.521,8.688,1.49,9.082,1.498,9.142c0.161,1.295,2.238,2.322,4.375,2.358C5.916,11.501,5.958,11.501,6,11.501c0.043,0,0.084,0,0.127-0.001c2.076-0.026,4.214-1.063,4.375-2.358C10.509,9.082,10.471,8.696,10.452,8.545z'/></g></g></svg>",
OFFLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path fill='#cccccc' d='M6.002,7.143C5.645,7.363,5.167,7.52,4.502,7.52c-2.493,0-2.5-2.02-2.5-2.02S1.029,5.607,0.775,6.004C0.41,6.577,0.15,7.716,0.049,8.545c-0.025,0.145-0.057,0.537-0.05,0.598c0.162,1.295,2.237,2.321,4.375,2.357c0.043,0.001,0.085,0.001,0.127,0.001c0.043,0,0.084,0,0.127-0.001c1.879-0.023,3.793-0.879,4.263-2h-2.89L6.002,7.143L6.002,7.143z M4.501,5.488c1.372,0,2.483-1.117,2.483-2.494c0-1.378-1.111-2.495-2.483-2.495c-1.371,0-2.481,1.117-2.481,2.495C2.02,4.371,3.13,5.488,4.501,5.488z M7.002,6.5v2h5v-2H7.002z'/></g></g></svg>",
MENU_ICON: "<svg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='4px' height='16px' viewBox='0 0 8 32' enable-background='new 0 0 8 32' xml:space='preserve'> <g> <circle cx='4' cy='4.062' r='4'/> <circle cx='4' cy='16' r='4'/> <circle cx='4' cy='28' r='4'/> </g> </svg>",
- COMMENT_ICON: "<svg version='1.1' id='Layer_2' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='15px' height='15px' viewBox='1 1.5 15 15' enable-background='new 1 1.5 15 15' xml:space='preserve'> <g> <g> <path fill='#211B1B' d='M14,1.5H3c-1.104,0-2,0.896-2,2v8c0,1.104,0.896,2,2,2h1.628l1.884,3l1.866-3H14c1.104,0,2-0.896,2-2v-8 C16,2.396,15.104,1.5,14,1.5z M15,11.5c0,0.553-0.447,1-1,1H8l-1.493,2l-1.504-1.991L5,12.5H3c-0.552,0-1-0.447-1-1v-8 c0-0.552,0.448-1,1-1h11c0.553,0,1,0.448,1,1V11.5z'/> </g> </g> </svg>"
+ COMMENT_ICON: "<svg version='1.1' id='Layer_2' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='15px' height='15px' viewBox='1 1.5 15 15' enable-background='new 1 1.5 15 15' xml:space='preserve'> <g> <g> <path fill='#211B1B' d='M14,1.5H3c-1.104,0-2,0.896-2,2v8c0,1.104,0.896,2,2,2h1.628l1.884,3l1.866-3H14c1.104,0,2-0.896,2-2v-8 C16,2.396,15.104,1.5,14,1.5z M15,11.5c0,0.553-0.447,1-1,1H8l-1.493,2l-1.504-1.991L5,12.5H3c-0.552,0-1-0.447-1-1v-8 c0-0.552,0.448-1,1-1h11c0.553,0,1,0.448,1,1V11.5z'/> </g> </g> </svg>",
+ THEMES: {
+ default: {
+ type: 'Mattermost',
+ sidebarBg: '#fafafa',
+ sidebarText: '#999999',
+ sidebarUnreadText: '#333333',
+ sidebarTextHoverBg: '#e6f2fa',
+ sidebarTextHoverColor: '#999999',
+ sidebarTextActiveBg: '#e1e1e1',
+ sidebarTextActiveColor: '#111111',
+ sidebarHeaderBg: '#2389d7',
+ sidebarHeaderTextColor: '#ffffff',
+ onlineIndicator: '#7DBE00',
+ mentionBj: '#2389d7',
+ mentionColor: '#ffffff',
+ centerChannelBg: '#ffffff',
+ centerChannelColor: '#333333',
+ newMessageSeparator: '#FF8800',
+ linkColor: '#2389d7',
+ buttonBg: '#2389d7',
+ buttonColor: '#FFFFFF'
+ },
+ organization: {
+ type: 'Organization',
+ sidebarBg: '#2071a7',
+ sidebarText: '#bfcde8',
+ sidebarUnreadText: '#fff',
+ sidebarTextHoverBg: '#136197',
+ sidebarTextHoverColor: '#bfcde8',
+ sidebarTextActiveBg: '#136197',
+ sidebarTextActiveColor: '#FFFFFF',
+ sidebarHeaderBg: '#2f81b7',
+ sidebarHeaderTextColor: '#FFFFFF',
+ onlineIndicator: '#7DBE00',
+ mentionBj: '#136197',
+ mentionColor: '#bfcde8',
+ centerChannelBg: '#f2f4f8',
+ centerChannelColor: '#333333',
+ newMessageSeparator: '#FF8800',
+ linkColor: '#2f81b7',
+ buttonBg: '#1dacfc',
+ buttonColor: '#FFFFFF'
+ },
+ mattermostDark: {
+ type: 'Mattermost Dark',
+ sidebarBg: '#1B2C3E',
+ sidebarText: '#bbbbbb',
+ sidebarUnreadText: '#fff',
+ sidebarTextHoverBg: '#4A5664',
+ sidebarTextHoverColor: '#bbbbbb',
+ sidebarTextActiveBg: '#39769C',
+ sidebarTextActiveColor: '#FFFFFF',
+ sidebarHeaderBg: '#1B2C3E',
+ sidebarHeaderTextColor: '#FFFFFF',
+ onlineIndicator: '#55C5B2',
+ mentionBj: '#B74A4A',
+ mentionColor: '#FFFFFF',
+ centerChannelBg: '#2F3E4E',
+ centerChannelColor: '#DDDDDD',
+ newMessageSeparator: '#5de5da',
+ linkColor: '#A4FFEB',
+ buttonBg: '#1dacfc',
+ buttonColor: '#FFFFFF'
+ },
+ windows10: {
+ type: 'Windows Dark',
+ sidebarBg: '#171717',
+ sidebarText: '#eee',
+ sidebarUnreadText: '#fff',
+ sidebarTextHoverBg: '#302e30',
+ sidebarTextHoverColor: '#fff',
+ sidebarTextActiveBg: '#484748',
+ sidebarTextActiveColor: '#FFFFFF',
+ sidebarHeaderBg: '#1f1f1f',
+ sidebarHeaderTextColor: '#FFFFFF',
+ onlineIndicator: '#0177e7',
+ mentionBj: '#0177e7',
+ mentionColor: '#FFFFFF',
+ centerChannelBg: '#1F1F1F',
+ centerChannelColor: '#DDDDDD',
+ newMessageSeparator: '#CC992D',
+ linkColor: '#0177e7',
+ buttonBg: '#0177e7',
+ buttonColor: '#FFFFFF'
+ }
+ },
+ THEME_ELEMENTS: [
+ {
+ id: 'sidebarBg',
+ uiName: 'Sidebar BG'
+ },
+ {
+ id: 'sidebarText',
+ uiName: 'Sidebar Text'
+ },
+ {
+ id: 'sidebarHeaderBg',
+ uiName: 'Sidebar Header BG'
+ },
+ {
+ id: 'sidebarHeaderTextColor',
+ uiName: 'Sidebar Header Text'
+ },
+ {
+ id: 'sidebarUnreadText',
+ uiName: 'Sidebar Unread Text'
+ },
+ {
+ id: 'sidebarTextHoverBg',
+ uiName: 'Sidebar Text Hover BG'
+ },
+ {
+ id: 'sidebarTextHoverColor',
+ uiName: 'Sidebar Text Hover Color'
+ },
+ {
+ id: 'sidebarTextActiveBg',
+ uiName: 'Sidebar Text Active BG'
+ },
+ {
+ id: 'sidebarTextActiveColor',
+ uiName: 'Sidebar Text Active Color'
+ },
+ {
+ id: 'onlineIndicator',
+ uiName: 'Online Indicator'
+ },
+ {
+ id: 'mentionBj',
+ uiName: 'Mention Jewel BG'
+ },
+ {
+ id: 'mentionColor',
+ uiName: 'Mention Jewel Text'
+ },
+ {
+ id: 'centerChannelBg',
+ uiName: 'Center Channel BG'
+ },
+ {
+ id: 'centerChannelColor',
+ uiName: 'Center Channel Text'
+ },
+ {
+ id: 'newMessageSeparator',
+ uiName: 'New message separator'
+ },
+ {
+ id: 'linkColor',
+ uiName: 'Link Color'
+ },
+ {
+ id: 'buttonBg',
+ uiName: 'Button BG'
+ },
+
+ {
+ id: 'buttonColor',
+ uiName: 'Button Text'
+ }
+ ]
};
diff --git a/web/react/utils/emoticons.jsx b/web/react/utils/emoticons.jsx
new file mode 100644
index 000000000..a7c837199
--- /dev/null
+++ b/web/react/utils/emoticons.jsx
@@ -0,0 +1,158 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+const emoticonPatterns = {
+ smile: /:-?\)/g, // :)
+ open_mouth: /:o/gi, // :o
+ scream: /:-o/gi, // :-o
+ smirk: /:-?]/g, // :]
+ grinning: /:-?d/gi, // :D
+ stuck_out_tongue_closed_eyes: /x-d/gi, // x-d
+ stuck_out_tongue_winking_eye: /:-?p/gi, // :p
+ rage: /:-?[\[@]/g, // :@
+ frowning: /:-?\(/g, // :(
+ sob: /:['’]-?\(|:&#x27;\(/g, // :`(
+ kissing_heart: /:-?\*/g, // :*
+ pensive: /:-?\//g, // :/
+ confounded: /:-?s/gi, // :s
+ flushed: /:-?\|/g, // :|
+ relaxed: /:-?\$/g, // :$
+ mask: /:-x/gi, // :-x
+ heart: /<3|&lt;3/g, // <3
+ broken_heart: /<\/3|&lt;&#x2F;3/g, // </3
+ thumbsup: /:\+1:/g, // :+1:
+ thumbsdown: /:\-1:/g // :-1:
+};
+
+function initializeEmoticonMap() {
+ const emoticonNames =
+ ('+1,-1,100,1234,8ball,a,ab,abc,abcd,accept,aerial_tramway,airplane,alarm_clock,alien,ambulance,anchor,angel,' +
+ 'anger,angry,anguished,ant,apple,aquarius,aries,arrow_backward,arrow_double_down,arrow_double_up,arrow_down,' +
+ 'arrow_down_small,arrow_forward,arrow_heading_down,arrow_heading_up,arrow_left,arrow_lower_left,' +
+ 'arrow_lower_right,arrow_right,arrow_right_hook,arrow_up,arrow_up_down,arrow_up_small,arrow_upper_left,' +
+ 'arrow_upper_right,arrows_clockwise,arrows_counterclockwise,art,articulated_lorry,astonished,atm,b,baby,' +
+ 'baby_bottle,baby_chick,baby_symbol,back,baggage_claim,balloon,ballot_box_with_check,bamboo,banana,bangbang,' +
+ 'bank,bar_chart,barber,baseball,basketball,bath,bathtub,battery,bear,bee,beer,beers,beetle,beginner,bell,bento,' +
+ 'bicyclist,bike,bikini,bird,birthday,black_circle,black_joker,black_medium_small_square,black_medium_square,' +
+ 'black_nib,black_small_square,black_square,black_square_button,blossom,blowfish,blue_book,blue_car,blue_heart,' +
+ 'blush,boar,boat,bomb,book,bookmark,bookmark_tabs,books,boom,boot,bouquet,bow,bowling,bowtie,boy,bread,' +
+ 'bride_with_veil,bridge_at_night,briefcase,broken_heart,bug,bulb,bullettrain_front,bullettrain_side,bus,busstop,' +
+ 'bust_in_silhouette,busts_in_silhouette,cactus,cake,calendar,calling,camel,camera,cancer,candy,capital_abcd,' +
+ 'capricorn,car,card_index,carousel_horse,cat,cat2,cd,chart,chart_with_downwards_trend,chart_with_upwards_trend,' +
+ 'checkered_flag,cherries,cherry_blossom,chestnut,chicken,children_crossing,chocolate_bar,christmas_tree,church,' +
+ 'cinema,circus_tent,city_sunrise,city_sunset,cl,clap,clapper,clipboard,clock1,clock10,clock1030,clock11,' +
+ 'clock1130,clock12,clock1230,clock130,clock2,clock230,clock3,clock330,clock4,clock430,clock5,clock530,clock6,' +
+ 'clock630,clock7,clock730,clock8,clock830,clock9,clock930,closed_book,closed_lock_with_key,closed_umbrella,cloud,' +
+ 'clubs,cn,cocktail,coffee,cold_sweat,collision,computer,confetti_ball,confounded,confused,congratulations,' +
+ 'construction,construction_worker,convenience_store,cookie,cool,cop,copyright,corn,couple,couple_with_heart,' +
+ 'couplekiss,cow,cow2,credit_card,crescent_moon,crocodile,crossed_flags,crown,cry,crying_cat_face,crystal_ball,' +
+ 'cupid,curly_loop,currency_exchange,curry,custard,customs,cyclone,dancer,dancers,dango,dart,dash,date,de,' +
+ 'deciduous_tree,department_store,diamond_shape_with_a_dot_inside,diamonds,disappointed,disappointed_relieved,' +
+ 'dizzy,dizzy_face,do_not_litter,dog,dog2,dollar,dolls,dolphin,donut,door,doughnut,dragon,dragon_face,dress,' +
+ 'dromedary_camel,droplet,dvd,e-mail,ear,ear_of_rice,earth_africa,earth_americas,earth_asia,egg,eggplant,eight,' +
+ 'eight_pointed_black_star,eight_spoked_asterisk,electric_plug,elephant,email,end,envelope,es,euro,' +
+ 'european_castle,european_post_office,evergreen_tree,exclamation,expressionless,eyeglasses,eyes,facepunch,' +
+ 'factory,fallen_leaf,family,fast_forward,fax,fearful,feelsgood,feet,ferris_wheel,file_folder,finnadie,fire,' +
+ 'fire_engine,fireworks,first_quarter_moon,first_quarter_moon_with_face,fish,fish_cake,fishing_pole_and_fish,fist,' +
+ 'five,flags,flashlight,floppy_disk,flower_playing_cards,flushed,foggy,football,fork_and_knife,fountain,four,' +
+ 'four_leaf_clover,fr,free,fried_shrimp,fries,frog,frowning,fu,fuelpump,full_moon,full_moon_with_face,game_die,gb,' +
+ 'gem,gemini,ghost,gift,gift_heart,girl,globe_with_meridians,goat,goberserk,godmode,golf,grapes,green_apple,' +
+ 'green_book,green_heart,grey_exclamation,grey_question,grimacing,grin,grinning,guardsman,guitar,gun,haircut,' +
+ 'hamburger,hammer,hamster,hand,handbag,hankey,hash,hatched_chick,hatching_chick,headphones,hear_no_evil,heart,' +
+ 'heart_decoration,heart_eyes,heart_eyes_cat,heartbeat,heartpulse,hearts,heavy_check_mark,heavy_division_sign,' +
+ 'heavy_dollar_sign,heavy_exclamation_mark,heavy_minus_sign,heavy_multiplication_x,heavy_plus_sign,helicopter,' +
+ 'herb,hibiscus,high_brightness,high_heel,hocho,honey_pot,honeybee,horse,horse_racing,hospital,hotel,hotsprings,' +
+ 'hourglass,hourglass_flowing_sand,house,house_with_garden,hurtrealbad,hushed,ice_cream,icecream,id,' +
+ 'ideograph_advantage,imp,inbox_tray,incoming_envelope,information_desk_person,information_source,innocent,' +
+ 'interrobang,iphone,it,izakaya_lantern,jack_o_lantern,japan,japanese_castle,japanese_goblin,japanese_ogre,jeans,' +
+ 'joy,joy_cat,jp,key,keycap_ten,kimono,kiss,kissing,kissing_cat,kissing_closed_eyes,kissing_face,kissing_heart,' +
+ 'kissing_smiling_eyes,koala,koko,kr,large_blue_circle,large_blue_diamond,large_orange_diamond,last_quarter_moon,' +
+ 'last_quarter_moon_with_face,laughing,leaves,ledger,left_luggage,left_right_arrow,leftwards_arrow_with_hook,' +
+ 'lemon,leo,leopard,libra,light_rail,link,lips,lipstick,lock,lock_with_ink_pen,lollipop,loop,loudspeaker,' +
+ 'love_hotel,love_letter,low_brightness,m,mag,mag_right,mahjong,mailbox,mailbox_closed,mailbox_with_mail,' +
+ 'mailbox_with_no_mail,man,man_with_gua_pi_mao,man_with_turban,mans_shoe,maple_leaf,mask,massage,meat_on_bone,' +
+ 'mega,melon,memo,mens,metal,metro,microphone,microscope,milky_way,minibus,minidisc,mobile_phone_off,' +
+ 'money_with_wings,moneybag,monkey,monkey_face,monorail,mortar_board,mount_fuji,mountain_bicyclist,' +
+ 'mountain_cableway,mountain_railway,mouse,mouse2,movie_camera,moyai,muscle,mushroom,musical_keyboard,' +
+ 'musical_note,musical_score,mute,nail_care,name_badge,neckbeard,necktie,negative_squared_cross_mark,' +
+ 'neutral_face,new,new_moon,new_moon_with_face,newspaper,ng,nine,no_bell,no_bicycles,no_entry,no_entry_sign,' +
+ 'no_good,no_mobile_phones,no_mouth,no_pedestrians,no_smoking,non-potable_water,nose,notebook,' +
+ 'notebook_with_decorative_cover,notes,nut_and_bolt,o,o2,ocean,octocat,octopus,oden,office,ok,ok_hand,' +
+ 'ok_woman,older_man,older_woman,on,oncoming_automobile,oncoming_bus,oncoming_police_car,oncoming_taxi,one,' +
+ 'open_file_folder,open_hands,open_mouth,ophiuchus,orange_book,outbox_tray,ox,package,page_facing_up,' +
+ 'page_with_curl,pager,palm_tree,panda_face,paperclip,parking,part_alternation_mark,partly_sunny,' +
+ 'passport_control,paw_prints,peach,pear,pencil,pencil2,penguin,pensive,performing_arts,persevere,' +
+ 'person_frowning,person_with_blond_hair,person_with_pouting_face,phone,pig,pig2,pig_nose,pill,pineapple,pisces,' +
+ 'pizza,plus1,point_down,point_left,point_right,point_up,point_up_2,police_car,poodle,poop,post_office,' +
+ 'postal_horn,postbox,potable_water,pouch,poultry_leg,pound,pouting_cat,pray,princess,punch,purple_heart,purse,' +
+ 'pushpin,put_litter_in_its_place,question,rabbit,rabbit2,racehorse,radio,radio_button,rage,rage1,rage2,rage3,' +
+ 'rage4,railway_car,rainbow,raised_hand,raised_hands,raising_hand,ram,ramen,rat,recycle,red_car,red_circle,' +
+ 'registered,relaxed,relieved,repeat,repeat_one,restroom,revolving_hearts,rewind,ribbon,rice,rice_ball,' +
+ 'rice_cracker,rice_scene,ring,rocket,roller_coaster,rooster,rose,rotating_light,round_pushpin,rowboat,ru,' +
+ 'rugby_football,runner,running,running_shirt_with_sash,sa,sagittarius,sailboat,sake,sandal,santa,satellite,' +
+ 'satisfied,saxophone,school,school_satchel,scissors,scorpius,scream,scream_cat,scroll,seat,secret,see_no_evil,' +
+ 'seedling,seven,shaved_ice,sheep,shell,ship,shipit,shirt,shit,shoe,shower,signal_strength,six,six_pointed_star,' +
+ 'ski,skull,sleeping,sleepy,slot_machine,small_blue_diamond,small_orange_diamond,small_red_triangle,' +
+ 'small_red_triangle_down,smile,smile_cat,smiley,smiley_cat,smiling_imp,smirk,smirk_cat,smoking,snail,snake,' +
+ 'snowboarder,snowflake,snowman,sob,soccer,soon,sos,sound,space_invader,spades,spaghetti,sparkle,sparkler,' +
+ 'sparkles,sparkling_heart,speak_no_evil,speaker,speech_balloon,speedboat,squirrel,star,star2,stars,station,' +
+ 'statue_of_liberty,steam_locomotive,stew,straight_ruler,strawberry,stuck_out_tongue,stuck_out_tongue_closed_eyes,' +
+ 'stuck_out_tongue_winking_eye,sun_with_face,sunflower,sunglasses,sunny,sunrise,sunrise_over_mountains,surfer,' +
+ 'sushi,suspect,suspension_railway,sweat,sweat_drops,sweat_smile,sweet_potato,swimmer,symbols,syringe,tada,' +
+ 'tanabata_tree,tangerine,taurus,taxi,tea,telephone,telephone_receiver,telescope,tennis,tent,thought_balloon,' +
+ 'three,thumbsdown,thumbsup,ticket,tiger,tiger2,tired_face,tm,toilet,tokyo_tower,tomato,tongue,top,tophat,' +
+ 'tractor,traffic_light,train,train2,tram,triangular_flag_on_post,triangular_ruler,trident,triumph,trolleybus,' +
+ 'trollface,trophy,tropical_drink,tropical_fish,truck,trumpet,tshirt,tulip,turtle,tv,twisted_rightwards_arrows,' +
+ 'two,two_hearts,two_men_holding_hands,two_women_holding_hands,u5272,u5408,u55b6,u6307,u6708,u6709,u6e80,u7121,' +
+ 'u7533,u7981,u7a7a,uk,umbrella,unamused,underage,unlock,up,us,v,vertical_traffic_light,vhs,vibration_mode,' +
+ 'video_camera,video_game,violin,virgo,volcano,vs,walking,waning_crescent_moon,waning_gibbous_moon,warning,watch,' +
+ 'water_buffalo,watermelon,wave,wavy_dash,waxing_crescent_moon,waxing_gibbous_moon,wc,weary,wedding,whale,whale2,' +
+ 'wheelchair,white_check_mark,white_circle,white_flower,white_large_square,white_medium_small_square,' +
+ 'white_medium_square,white_small_square,white_square_button,wind_chime,wine_glass,wink,wolf,woman,' +
+ 'womans_clothes,womans_hat,womens,worried,wrench,x,yellow_heart,yen,yum,zap,zero,zzz').split(',');
+
+ // use a map to help make lookups faster instead of having to use indexOf on an array
+ const out = new Map();
+
+ for (let i = 0; i < emoticonNames.length; i++) {
+ out[emoticonNames[i]] = true;
+ }
+
+ return out;
+}
+
+const emoticonMap = initializeEmoticonMap();
+
+export function handleEmoticons(text, tokens) {
+ let output = text;
+
+ function replaceEmoticonWithToken(match, name) {
+ if (emoticonMap[name]) {
+ const index = tokens.size;
+ const alias = `MM_EMOTICON${index}`;
+
+ tokens.set(alias, {
+ value: `<img align="absmiddle" alt=${match} class="emoji" src=${getImagePathForEmoticon(name)} title=${match} />`,
+ originalText: match
+ });
+
+ return alias;
+ }
+
+ return match;
+ }
+
+ output = output.replace(/:([a-zA-Z0-9_-]+):/g, replaceEmoticonWithToken);
+
+ $.each(emoticonPatterns, (name, pattern) => {
+ // this might look a bit funny, but since the name isn't contained in the actual match
+ // like with the named emoticons, we need to add it in manually
+ output = output.replace(pattern, (match) => replaceEmoticonWithToken(match, name));
+ });
+
+ return output;
+}
+
+function getImagePathForEmoticon(name) {
+ return `/static/images/emoji/${name}.png`;
+}
diff --git a/web/react/utils/markdown.jsx b/web/react/utils/markdown.jsx
index 96da54217..7e88f8644 100644
--- a/web/react/utils/markdown.jsx
+++ b/web/react/utils/markdown.jsx
@@ -1,9 +1,33 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
+const TextFormatting = require('./text_formatting.jsx');
+
const marked = require('marked');
export class MattermostMarkdownRenderer extends marked.Renderer {
+ constructor(options, formattingOptions = {}) {
+ super(options);
+
+ this.heading = this.heading.bind(this);
+ this.text = this.text.bind(this);
+
+ this.formattingOptions = formattingOptions;
+ }
+
+ br() {
+ if (this.formattingOptions.singleline) {
+ return ' ';
+ }
+
+ return super.br();
+ }
+
+ heading(text, level, raw) {
+ const id = `${this.options.headerPrefix}${raw.toLowerCase().replace(/[^\w]+/g, '-')}`;
+ return `<h${level} id="${id}" class="markdown__heading">${text}</h${level}>`;
+ }
+
link(href, title, text) {
let outHref = href;
@@ -11,12 +35,28 @@ export class MattermostMarkdownRenderer extends marked.Renderer {
outHref = `http://${outHref}`;
}
- let output = '<a class="theme" href="' + outHref + '"';
+ let output = '<a class="theme markdown__link" href="' + outHref + '"';
if (title) {
output += ' title="' + title + '"';
}
- output += '>' + text + '</a>';
+ output += ' target="_blank">' + text + '</a>';
return output;
}
+
+ paragraph(text) {
+ if (this.formattingOptions.singleline) {
+ return `<p class="markdown__paragraph-inline">${text}</p>`;
+ }
+
+ return super.paragraph(text);
+ }
+
+ table(header, body) {
+ return `<table class="markdown__table"><thead>${header}</thead><tbody>${body}</tbody></table>`;
+ }
+
+ text(text) {
+ return TextFormatting.doFormatText(text, this.formattingOptions);
+ }
}
diff --git a/web/react/utils/text_formatting.jsx b/web/react/utils/text_formatting.jsx
index 4e390f708..56bf49c3f 100644
--- a/web/react/utils/text_formatting.jsx
+++ b/web/react/utils/text_formatting.jsx
@@ -3,41 +3,58 @@
const Autolinker = require('autolinker');
const Constants = require('./constants.jsx');
+const Emoticons = require('./emoticons.jsx');
const Markdown = require('./markdown.jsx');
const UserStore = require('../stores/user_store.jsx');
const Utils = require('./utils.jsx');
const marked = require('marked');
-const markdownRenderer = new Markdown.MattermostMarkdownRenderer();
-
// Performs formatting of user posts including highlighting mentions and search terms and converting urls, hashtags, and
// @mentions to links by taking a user's message and returning a string of formatted html. Also takes a number of options
// as part of the second parameter:
// - searchTerm - If specified, this word is highlighted in the resulting html. Defaults to nothing.
// - mentionHighlight - Specifies whether or not to highlight mentions of the current user. Defaults to true.
// - singleline - Specifies whether or not to remove newlines. Defaults to false.
+// - emoticons - Enables emoticon parsing. Defaults to true.
// - markdown - Enables markdown parsing. Defaults to true.
export function formatText(text, options = {}) {
- if (!('markdown' in options)) {
- options.markdown = true;
- }
-
- // wait until marked can sanitize the html so that we don't break markdown block quotes
let output;
- if (!options.markdown) {
- output = sanitizeHtml(text);
+
+ if (!('markdown' in options) || options.markdown) {
+ // the markdown renderer will call doFormatText as necessary so just call marked
+ output = marked(text, {
+ renderer: new Markdown.MattermostMarkdownRenderer(null, options),
+ sanitize: true
+ });
} else {
- output = text;
+ output = sanitizeHtml(text);
+ output = doFormatText(output, options);
+ }
+
+ // replace newlines with spaces if necessary
+ if (options.singleline) {
+ output = replaceNewlines(output);
}
+ return output;
+}
+
+// Performs most of the actual formatting work for formatText. Not intended to be called normally.
+export function doFormatText(text, options) {
+ let output = text;
+
const tokens = new Map();
// replace important words and phrases with tokens
- output = autolinkUrls(output, tokens, !!options.markdown);
+ output = autolinkUrls(output, tokens);
output = autolinkAtMentions(output, tokens);
output = autolinkHashtags(output, tokens);
+ if (!('emoticons' in options) || options.emoticon) {
+ output = Emoticons.handleEmoticons(output, tokens);
+ }
+
if (options.searchTerm) {
output = highlightSearchTerm(output, tokens, options.searchTerm);
}
@@ -46,22 +63,9 @@ export function formatText(text, options = {}) {
output = highlightCurrentMentions(output, tokens);
}
- // perform markdown parsing while we have an html-free input string
- if (options.markdown) {
- output = marked(output, {
- renderer: markdownRenderer,
- sanitize: true
- });
- }
-
// reinsert tokens with formatted versions of the important words and phrases
output = replaceTokens(output, tokens);
- // replace newlines with html line breaks
- if (options.singleline) {
- output = replaceNewlines(output);
- }
-
return output;
}
@@ -78,7 +82,7 @@ export function sanitizeHtml(text) {
return output;
}
-function autolinkUrls(text, tokens, markdown) {
+function autolinkUrls(text, tokens) {
function replaceUrlWithToken(autolinker, match) {
const linkText = match.getMatchedText();
let url = linkText;
@@ -108,30 +112,7 @@ function autolinkUrls(text, tokens, markdown) {
replaceFn: replaceUrlWithToken
});
- let output = text;
-
- // temporarily replace markdown links if markdown is enabled so that we don't accidentally parse them twice
- const markdownLinkTokens = new Map();
- if (markdown) {
- function replaceMarkdownLinkWithToken(markdownLink) {
- const index = markdownLinkTokens.size;
- const alias = `MM_MARKDOWNLINK${index}`;
-
- markdownLinkTokens.set(alias, {value: markdownLink});
-
- return alias;
- }
-
- output = output.replace(/\]\([^\)]*\)/g, replaceMarkdownLinkWithToken);
- }
-
- output = autolinker.link(output);
-
- if (markdown) {
- output = replaceTokens(output, markdownLinkTokens);
- }
-
- return output;
+ return autolinker.link(text);
}
function autolinkAtMentions(text, tokens) {
@@ -241,7 +222,7 @@ function autolinkHashtags(text, tokens) {
return prefix + alias;
}
- return output.replace(/(^|\W)(#[a-zA-Z0-9.\-_]+)\b/g, replaceHashtagWithToken);
+ return output.replace(/(^|\W)(#[a-zA-Z][a-zA-Z0-9.\-_]*)\b/g, replaceHashtagWithToken);
}
function highlightSearchTerm(text, tokens, searchTerm) {
diff --git a/web/react/utils/utils.jsx b/web/react/utils/utils.jsx
index 074591489..61dcae6d8 100644
--- a/web/react/utils/utils.jsx
+++ b/web/react/utils/utils.jsx
@@ -4,6 +4,7 @@
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var ChannelStore = require('../stores/channel_store.jsx');
var UserStore = require('../stores/user_store.jsx');
+var TeamStore = require('../stores/team_store.jsx');
var Constants = require('../utils/constants.jsx');
var ActionTypes = Constants.ActionTypes;
var AsyncClient = require('./async_client.jsx');
@@ -113,7 +114,7 @@ export function notifyMe(title, body, channel) {
if (channel) {
switchChannel(channel);
} else {
- window.location.href = '/';
+ window.location.href = TeamStore.getCurrentTeamUrl() + '/channels/town-square';
}
};
setTimeout(function closeNotificationOnTimeout() {
@@ -314,7 +315,6 @@ function getYoutubeEmbed(link) {
$('.video-type.' + youtubeId).html('Youtube - ');
$('.video-uploader.' + youtubeId).html(metadata.channelTitle);
$('.video-title.' + youtubeId).find('a').html(metadata.title);
- $('.post-list-holder-by-time').scrollTop($('.post-list-holder-by-time')[0].scrollHeight);
}
if (global.window.config.GoogleDeveloperKey) {
@@ -542,7 +542,131 @@ export function toTitleCase(str) {
return str.replace(/\w\S*/g, doTitleCase);
}
-export function changeCss(className, classValue) {
+export function applyTheme(theme) {
+ if (theme.sidebarBg) {
+ changeCss('.sidebar--left', 'background:' + theme.sidebarBg, 1);
+ changeCss('@media(max-width: 768px){.search-bar__container', 'background:' + theme.sidebarBg, 1);
+ }
+
+ if (theme.sidebarText) {
+ changeCss('.sidebar--left .nav li>a, .sidebar--right', 'color:' + theme.sidebarText, 1);
+ changeCss('.sidebar--left .nav li>h4, .sidebar--left .add-channel-btn', 'color:' + changeOpacity(theme.sidebarText, 0.8), 1);
+ changeCss('.sidebar--left .add-channel-btn:hover, .sidebar--left .add-channel-btn:focus', 'color:' + theme.sidebarText, 1);
+ changeCss('.sidebar--left, .sidebar--right .sidebar--right__header', 'border-color:' + changeOpacity(theme.sidebarText, 0.2), 1);
+ changeCss('.sidebar--left .status path', 'fill:' + changeOpacity(theme.sidebarText, 0.5), 1);
+ }
+
+ if (theme.sidebarUnreadText) {
+ changeCss('.sidebar--left .nav li>a.unread-title', 'color:' + theme.sidebarUnreadText + '!important;', 1);
+ }
+
+ if (theme.sidebarTextHoverBg) {
+ changeCss('.sidebar--left .nav li>a:hover, .sidebar--left .nav li>a:focus', 'background:' + theme.sidebarTextHoverBg, 1);
+ }
+
+ if (theme.sidebarTextHoverColor) {
+ changeCss('.sidebar--left .nav li>a:hover, .sidebar--left .nav li>a:focus', 'color:' + theme.sidebarTextHoverColor, 2);
+ }
+
+ if (theme.sidebarTextActiveBg) {
+ changeCss('.sidebar--left .nav li.active a, .sidebar--left .nav li.active a:hover, .sidebar--left .nav li.active a:focus', 'background:' + theme.sidebarTextActiveBg, 1);
+ }
+
+ if (theme.sidebarTextActiveColor) {
+ changeCss('.sidebar--left .nav li.active a, .sidebar--left .nav li.active a:hover, .sidebar--left .nav li.active a:focus', 'color:' + theme.sidebarTextActiveColor, 2);
+ }
+
+ if (theme.sidebarHeaderBg) {
+ changeCss('.sidebar--left .team__header, .sidebar--menu .team__header', 'background:' + theme.sidebarHeaderBg, 1);
+ changeCss('.modal .modal-header', 'background:' + theme.sidebarHeaderBg, 1);
+ changeCss('#navbar .navbar-default', 'background:' + theme.sidebarHeaderBg, 1);
+ }
+
+ if (theme.sidebarHeaderTextColor) {
+ changeCss('.sidebar--left .team__header .header__info, .sidebar--menu .team__header .header__info', 'color:' + theme.sidebarHeaderTextColor, 1);
+ changeCss('.sidebar--left .team__header .user__name, .sidebar--menu .team__header .user__name', 'color:' + changeOpacity(theme.sidebarHeaderTextColor, 0.8), 1);
+ changeCss('.sidebar--left .team__header:hover .user__name, .sidebar--menu .team__header:hover .user__name', 'color:' + theme.sidebarHeaderTextColor, 1);
+ changeCss('.modal .modal-header .modal-title, .modal .modal-header .modal-title .name, .modal .modal-header button.close', 'color:' + theme.sidebarHeaderTextColor, 1);
+ changeCss('#navbar .navbar-default .navbar-brand .heading, ', 'color:' + theme.sidebarHeaderTextColor, 1);
+ changeCss('#navbar .navbar-default .navbar-toggle .icon-bar, ', 'background:' + theme.sidebarHeaderTextColor, 1);
+ }
+
+ if (theme.onlineIndicator) {
+ changeCss('.sidebar--left .status .online--icon', 'fill:' + theme.onlineIndicator, 1);
+ }
+
+ if (theme.mentionBj) {
+ changeCss('.sidebar--left .nav-pills__unread-indicator', 'background:' + theme.mentionBj, 1);
+ changeCss('.sidebar--left .badge', 'background:' + theme.mentionBj, 1);
+ }
+
+ if (theme.mentionColor) {
+ changeCss('.sidebar--left .nav-pills__unread-indicator', 'color:' + theme.mentionColor, 2);
+ changeCss('.sidebar--left .badge', 'color:' + theme.mentionColor, 2);
+ }
+
+ if (theme.centerChannelBg) {
+ changeCss('.app__content, .markdown__table, .markdown__table tbody tr', 'background:' + theme.centerChannelBg, 1);
+ changeCss('#post-list .post-list-holder-by-time', 'background:' + theme.centerChannelBg, 1);
+ changeCss('#post-create', 'background:' + theme.centerChannelBg, 1);
+ changeCss('.search-bar__container .search__form .search-bar', 'background:' + theme.centerChannelBg, 1);
+ changeCss('.date-separator .separator__text, .new-separator .separator__text', 'background:' + theme.centerChannelBg, 1);
+ changeCss('.post-image__column .post-image__details', 'background:' + theme.centerChannelBg, 1);
+ changeCss('.sidebar--right', 'background:' + theme.centerChannelBg, 1);
+ }
+
+ if (theme.centerChannelColor) {
+ changeCss('.app__content, .post-create__container .post-create-body .btn-file, .post-create__container .post-create-footer .msg-typing, .loading-screen .loading__content .round', 'color:' + theme.centerChannelColor, 1);
+ changeCss('#post-create', 'color:' + theme.centerChannelColor, 2);
+ changeCss('.post-body hr', 'background:' + theme.centerChannelColor, 1);
+ changeCss('.channel-header .heading', 'color:' + theme.centerChannelColor, 1);
+ changeCss('.markdown__table tbody tr:nth-child(2n)', 'background:' + changeOpacity(theme.centerChannelColor, 0.07), 1);
+ changeCss('.channel-header__info>div.dropdown .header-dropdown__icon', 'color:' + changeOpacity(theme.centerChannelColor, 0.8), 1);
+ changeCss('.channel-header #member_popover', 'color:' + changeOpacity(theme.centerChannelColor, 0.8), 1);
+ changeCss('.custom-textarea, .custom-textarea:focus, .preview-container .preview-div, .post-image__column .post-image__details, .sidebar--right .sidebar-right__body, .markdown__table th, .markdown__table td', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2), 1);
+ changeCss('.custom-textarea', 'color:' + theme.centerChannelColor, 1);
+ changeCss('.post-image__column', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2), 2);
+ changeCss('.post-image__column .post-image__details', 'color:' + theme.centerChannelColor, 2);
+ changeCss('.post-image__column a, .post-image__column a:hover, .post-image__column a:focus', 'color:' + theme.centerChannelColor, 1);
+ changeCss('.search-bar__container .search__form .search-bar', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2) + '; color: ' + theme.centerChannelColor, 2);
+ changeCss('.search-bar__container .search__form', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2), 1);
+ changeCss('.channel-intro .channel-intro__content', 'background:' + changeOpacity(theme.centerChannelColor, 0.05), 1);
+ changeCss('.date-separator .separator__text', 'color:' + theme.centerChannelColor, 2);
+ changeCss('.date-separator .separator__hr, .post-right__container .post.post--root hr, .search-item-container', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2), 1);
+ changeCss('.channel-intro', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.2), 1);
+ changeCss('.post.current--user .post-body, .post.post--comment.other--root.current--user .post-comment', 'background:' + changeOpacity(theme.centerChannelColor, 0.07), 1);
+ changeCss('.post.current--user .post-body, .post.post--comment.other--root.current--user .post-comment, .post.post--comment.other--root .post-comment, .post.same--root .post-body', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.07), 2);
+ changeCss('@media(max-width: 1440px){.post.same--root', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.07), 2);
+ changeCss('@media(max-width: 1440px){.post.same--root', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.07), 2);
+ changeCss('@media(max-width: 1800px){.inner__wrap.move--left .post.post--comment.same--root', 'border-color:' + changeOpacity(theme.centerChannelColor, 0.07), 2);
+ changeCss('.post:hover, .sidebar--right .sidebar--right__header', 'background:' + changeOpacity(theme.centerChannelColor, 0.07), 1);
+ changeCss('.date-separator.hovered--before:after, .new-separator.hovered--before:after', 'background:' + changeOpacity(theme.centerChannelColor, 0.07), 1);
+ changeCss('.date-separator.hovered--after:before, .new-separator.hovered--after:before', 'background:' + changeOpacity(theme.centerChannelColor, 0.07), 1);
+ changeCss('.post.current--user:hover .post-body ', 'background: none;', 1);
+ changeCss('.sidebar--right', 'color:' + theme.centerChannelColor, 2);
+ }
+
+ if (theme.newMessageSeparator) {
+ changeCss('.new-separator .separator__text', 'color:' + theme.newMessageSeparator, 1);
+ changeCss('.new-separator .separator__hr', 'border-color:' + changeOpacity(theme.newMessageSeparator, 0.5), 1);
+ }
+
+ if (theme.linkColor) {
+ changeCss('a, a:focus, a:hover', 'color:' + theme.linkColor, 1);
+ changeCss('.post .comment-icon__container', 'fill:' + theme.linkColor, 1);
+ }
+
+ if (theme.buttonBg) {
+ changeCss('.btn.btn-primary', 'background:' + theme.buttonBg, 1);
+ changeCss('.btn.btn-primary:hover, .btn.btn-primary:active, .btn.btn-primary:focus', 'background:' + changeColor(theme.buttonBg, -0.25), 1);
+ }
+
+ if (theme.buttonColor) {
+ changeCss('.btn.btn-primary', 'color:' + theme.buttonColor, 2);
+ }
+}
+
+export function changeCss(className, classValue, classRepeat) {
// we need invisible container to store additional css definitions
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length === 0) {
@@ -552,9 +676,9 @@ export function changeCss(className, classValue) {
}
// and we need one div for each class
- var classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
+ var classContainer = cssMainContainer.find('div[data-class="' + className + classRepeat + '"]');
if (classContainer.length === 0) {
- classContainer = $('<div data-class="' + className + '"></div>');
+ classContainer = $('<div data-class="' + className + classRepeat + '"></div>');
classContainer.appendTo(cssMainContainer);
}
@@ -760,57 +884,47 @@ Image.prototype.load = function imageLoad(url, progressCallback) {
Image.prototype.completedPercentage = 0;
export function changeColor(colourIn, amt) {
- var usePound = false;
- var col = colourIn;
-
- if (col[0] === '#') {
- col = col.slice(1);
- usePound = true;
- }
+ var hex = colourIn;
+ var lum = amt;
- var num = parseInt(col, 16);
-
- var r = (num >> 16) + amt;
-
- if (r > 255) {
- r = 255;
- } else if (r < 0) {
- r = 0;
+ // validate hex string
+ hex = String(hex).replace(/[^0-9a-f]/gi, '');
+ if (hex.length < 6) {
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
+ lum = lum || 0;
- var b = ((num >> 8) & 0x00FF) + amt;
-
- if (b > 255) {
- b = 255;
- } else if (b < 0) {
- b = 0;
+ // convert to decimal and change luminosity
+ var rgb = '#';
+ var c;
+ var i;
+ for (i = 0; i < 3; i++) {
+ c = parseInt(hex.substr(i * 2, 2), 16);
+ c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
+ rgb += ('00' + c).substr(c.length);
}
- var g = (num & 0x0000FF) + amt;
-
- if (g > 255) {
- g = 255;
- } else if (g < 0) {
- g = 0;
- }
+ return rgb;
+}
- var pound = '#';
- if (!usePound) {
- pound = '';
+export function changeOpacity(oldColor, opacity) {
+ var color = oldColor;
+ if (color[0] === '#') {
+ color = color.slice(1);
}
- return pound + String('000000' + (g | (b << 8) | (r << 16)).toString(16)).slice(-6);
-}
+ if (color.length === 3) {
+ const tempColor = color;
+ color = '';
-export function changeOpacity(oldColor, opacity) {
- var col = oldColor;
- if (col[0] === '#') {
- col = col.slice(1);
+ color += tempColor[0] + tempColor[0];
+ color += tempColor[1] + tempColor[1];
+ color += tempColor[2] + tempColor[2];
}
- var r = parseInt(col.substring(0, 2), 16);
- var g = parseInt(col.substring(2, 4), 16);
- var b = parseInt(col.substring(4, 6), 16);
+ var r = parseInt(color.substring(0, 2), 16);
+ var g = parseInt(color.substring(2, 4), 16);
+ var b = parseInt(color.substring(4, 6), 16);
return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')';
}
@@ -955,7 +1069,8 @@ export function getTeamURLFromAddressBar() {
export function getShortenedTeamURL() {
const teamURL = getTeamURLFromAddressBar();
- if (teamURL.length > 24) {
+ if (teamURL.length > 35) {
return teamURL.substring(0, 10) + '...' + teamURL.substring(teamURL.length - 12, teamURL.length) + '/';
}
+ return teamURL + '/';
}
diff --git a/web/sass-files/sass/partials/_admin-console.scss b/web/sass-files/sass/partials/_admin-console.scss
index 9823d2611..11794a269 100644
--- a/web/sass-files/sass/partials/_admin-console.scss
+++ b/web/sass-files/sass/partials/_admin-console.scss
@@ -1,5 +1,5 @@
-.sidebar--left {
- &.sidebar--collapsable {
+
+.sidebar--left { &.sidebar--collapsable {
background: #333;
.team__header {
background: transparent;
@@ -9,7 +9,7 @@
li {
padding: 0;
.icon {
- width: 15px;
+ width: 17px;
}
> a {
color: #fff;
@@ -19,6 +19,11 @@
background-color: $primary-color;
}
}
+ > h4 {
+ background: #333;
+ padding: 10px 10px;
+ margin: 1px 0 0;
+ }
}
.menu-icon--right {
vertical-align: top;
@@ -29,12 +34,15 @@
font-size: 13px;
right: -2px;
position: relative;
+ color: #fff;
}
}
&.nav__sub-menu {
- padding: 5px 0;
background: #111;
-webkit-font-smoothing: auto;
+ &.padded {
+ padding: 5px 0;
+ }
li {
> a {
font-size: 13px;
@@ -88,6 +96,7 @@
overflow: auto;
background-color: #f1f1f1;
padding: 0 20px 20px;
+ min-height: 600px;
}
.wrapper--fixed {
max-width: 800px;
diff --git a/web/sass-files/sass/partials/_base.scss b/web/sass-files/sass/partials/_base.scss
index cdc2152e9..87d9b8200 100644
--- a/web/sass-files/sass/partials/_base.scss
+++ b/web/sass-files/sass/partials/_base.scss
@@ -34,20 +34,27 @@ body {
}
}
-b, strong {
- font-weight: 600;
+.popover {
+ color: #333;
+ a {
+ color: $primary-color;
+ &:hover, &:focus {
+ color: $primary-color;
+ }
+ }
}
-a {
- word-break: break-word;
+.word-break--all {
+ word-break: break-all;
}
-a.theme {
+a {
+ word-break: break-word;
color: $primary-color;
}
-div.theme {
- background-color: $primary-color;
+a:focus, a:hover {
+ color: $primary-color;
}
.tooltip {
diff --git a/web/sass-files/sass/partials/_colorpicker.scss b/web/sass-files/sass/partials/_colorpicker.scss
new file mode 100644
index 000000000..431f9d8d0
--- /dev/null
+++ b/web/sass-files/sass/partials/_colorpicker.scss
@@ -0,0 +1,251 @@
+/*!
+ * Bootstrap Colorpicker
+ * http://mjolnic.github.io/bootstrap-colorpicker/
+ *
+ * Originally written by (c) 2012 Stefan Petre
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0.txt
+ *
+ */
+
+.colorpicker-saturation {
+ float: left;
+ width: 100px;
+ height: 100px;
+ cursor: crosshair;
+ background-image: url("../images/bootstrap-colorpicker/saturation.png");
+}
+
+.colorpicker-saturation i {
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: block;
+ width: 5px;
+ height: 5px;
+ margin: -4px 0 0 -4px;
+ border: 1px solid #000;
+ -webkit-border-radius: 5px;
+ -moz-border-radius: 5px;
+ border-radius: 5px;
+}
+
+.colorpicker-saturation i b {
+ display: block;
+ width: 5px;
+ height: 5px;
+ border: 1px solid #fff;
+ -webkit-border-radius: 5px;
+ -moz-border-radius: 5px;
+ border-radius: 5px;
+}
+
+.colorpicker-hue,
+.colorpicker-alpha {
+ float: left;
+ width: 15px;
+ height: 100px;
+ margin-bottom: 4px;
+ margin-left: 4px;
+ cursor: row-resize;
+}
+
+.colorpicker-hue i,
+.colorpicker-alpha i {
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: block;
+ width: 100%;
+ height: 1px;
+ margin-top: -1px;
+ background: #000;
+ border-top: 1px solid #fff;
+}
+
+.colorpicker-hue {
+ background-image: url("../images/bootstrap-colorpicker/hue.png");
+}
+
+.colorpicker-alpha {
+ display: none;
+ background-image: url("../images/bootstrap-colorpicker/alpha.png");
+}
+
+.colorpicker-saturation,
+.colorpicker-hue,
+.colorpicker-alpha {
+ background-size: contain;
+}
+
+.colorpicker {
+ top: 0;
+ left: 0;
+ z-index: 2500;
+ min-width: 130px;
+ padding: 4px;
+ margin-top: 1px;
+ -webkit-border-radius: 4px;
+ -moz-border-radius: 4px;
+ border-radius: 4px;
+ *zoom: 1;
+}
+
+.colorpicker:before,
+.colorpicker:after {
+ display: table;
+ line-height: 0;
+ content: "";
+}
+
+.colorpicker:after {
+ clear: both;
+}
+
+.colorpicker:before {
+ position: absolute;
+ top: -7px;
+ left: 6px;
+ display: inline-block;
+ border-right: 7px solid transparent;
+ border-bottom: 7px solid #ccc;
+ border-left: 7px solid transparent;
+ border-bottom-color: rgba(0, 0, 0, 0.2);
+ content: '';
+}
+
+.colorpicker:after {
+ position: absolute;
+ top: -6px;
+ left: 7px;
+ display: inline-block;
+ border-right: 6px solid transparent;
+ border-bottom: 6px solid #ffffff;
+ border-left: 6px solid transparent;
+ content: '';
+}
+
+.colorpicker div {
+ position: relative;
+}
+
+.colorpicker.colorpicker-with-alpha {
+ min-width: 140px;
+}
+
+.colorpicker.colorpicker-with-alpha .colorpicker-alpha {
+ display: block;
+}
+
+.colorpicker-color {
+ height: 10px;
+ margin-top: 5px;
+ clear: both;
+ background-image: url("../images/bootstrap-colorpicker/alpha.png");
+ background-position: 0 100%;
+}
+
+.colorpicker-color div {
+ height: 10px;
+}
+
+.colorpicker-selectors {
+ display: none;
+ height: 10px;
+ margin-top: 5px;
+ clear: both;
+}
+
+.colorpicker-selectors i {
+ float: left;
+ width: 10px;
+ height: 10px;
+ cursor: pointer;
+}
+
+.colorpicker-selectors i + i {
+ margin-left: 3px;
+}
+
+.colorpicker-element .input-group-addon i,
+.colorpicker-element .add-on i {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ vertical-align: text-top;
+ cursor: pointer;
+}
+
+.colorpicker.colorpicker-inline {
+ position: relative;
+ z-index: auto;
+ display: inline-block;
+ float: none;
+}
+
+.colorpicker.colorpicker-horizontal {
+ width: 110px;
+ height: auto;
+ min-width: 110px;
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-saturation {
+ margin-bottom: 4px;
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-color {
+ width: 100px;
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-hue,
+.colorpicker.colorpicker-horizontal .colorpicker-alpha {
+ float: left;
+ width: 100px;
+ height: 15px;
+ margin-bottom: 4px;
+ margin-left: 0;
+ cursor: col-resize;
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-hue i,
+.colorpicker.colorpicker-horizontal .colorpicker-alpha i {
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: block;
+ width: 1px;
+ height: 15px;
+ margin-top: 0;
+ background: #ffffff;
+ border: none;
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-hue {
+ background-image: url("../images/bootstrap-colorpicker/hue-horizontal.png");
+}
+
+.colorpicker.colorpicker-horizontal .colorpicker-alpha {
+ background-image: url("../images/bootstrap-colorpicker/alpha-horizontal.png");
+}
+
+.colorpicker.colorpicker-hidden {
+ display: none;
+}
+
+.colorpicker.colorpicker-visible {
+ display: block;
+}
+
+.colorpicker-inline.colorpicker-visible {
+ display: inline-block;
+}
+
+.colorpicker-right:before {
+ right: 6px;
+ left: auto;
+}
+
+.colorpicker-right:after {
+ right: 7px;
+ left: auto;
+} \ No newline at end of file
diff --git a/web/sass-files/sass/partials/_files.scss b/web/sass-files/sass/partials/_files.scss
index 405265f92..6dbb82810 100644
--- a/web/sass-files/sass/partials/_files.scss
+++ b/web/sass-files/sass/partials/_files.scss
@@ -157,23 +157,23 @@
border-left: 1px solid #ddd;
font-size: 13px;
padding: 7px;
+ color: #333;
.post-image__name {
margin-bottom: 3px;
display: block;
- color: #333;
}
.post-image__download {
display: inline-block;
padding-right: 7px;
cursor: pointer;
- color: #555;
+ @include opacity(0.7);
}
.post-image__type {
- color: grey;
+ @include opacity(0.6);
}
.post-image__size {
margin-left: 4px;
- color: grey;
+ @include opacity(0.6);
}
}
a {
@@ -214,4 +214,3 @@
}
}
}
-
diff --git a/web/sass-files/sass/partials/_forms.scss b/web/sass-files/sass/partials/_forms.scss
index c8b08f44d..65ea161d4 100644
--- a/web/sass-files/sass/partials/_forms.scss
+++ b/web/sass-files/sass/partials/_forms.scss
@@ -18,6 +18,7 @@
.input__help {
color: #777;
margin: 10px 0 0 10px;
+ word-break: break-word;
&.dark {
color: #222;
}
diff --git a/web/sass-files/sass/partials/_headers.scss b/web/sass-files/sass/partials/_headers.scss
index 702f0fd60..b5fcb6145 100644
--- a/web/sass-files/sass/partials/_headers.scss
+++ b/web/sass-files/sass/partials/_headers.scss
@@ -39,6 +39,7 @@
text-overflow: ellipsis;
color: #888;
margin-top: 2px;
+ max-height: 45px;
}
&.popover {
white-space: normal;
@@ -231,6 +232,10 @@
width: 45px;
color: #999;
cursor: pointer;
+ .fa {
+ margin-left: 3px;
+ font-size: 16px;
+ }
}
&.alt {
margin: 0;
diff --git a/web/sass-files/sass/partials/_loading.scss b/web/sass-files/sass/partials/_loading.scss
index d71055722..ab8601df6 100644
--- a/web/sass-files/sass/partials/_loading.scss
+++ b/web/sass-files/sass/partials/_loading.scss
@@ -37,4 +37,4 @@
to { opacity: 0.1; }
}
}
-}
+} \ No newline at end of file
diff --git a/web/sass-files/sass/partials/_markdown.scss b/web/sass-files/sass/partials/_markdown.scss
new file mode 100644
index 000000000..122586354
--- /dev/null
+++ b/web/sass-files/sass/partials/_markdown.scss
@@ -0,0 +1,67 @@
+.markdown__heading {
+ font-weight: 700;
+}
+.markdown__paragraph-inline {
+ display: inline;
+ + .markdown__paragraph-inline {
+ margin-left: 4px;
+ }
+}
+.post-body {
+ hr {
+ height: 4px;
+ padding: 0;
+ margin: 15px 0 16px;
+ background-color: #e7e7e7;
+ border: 0 none;
+ @include opacity(0.2);
+ }
+}
+.markdown__table {
+ background: #fff;
+ margin: 5px 0 10px;
+ th, td {
+ padding: 6px 13px;
+ border: 1px solid #ddd;
+ }
+ tbody tr {
+ background: #fff;
+ &:nth-child(2n) {
+ background-color: #f8f8f8;
+ }
+ }
+}
+blockquote {
+ border: none;
+ position: relative;
+ font-size: 16px;
+ padding: 10px 10px 10px 38px;
+ margin-bottom: 0;
+ &:before {
+ font-family: FontAwesome;
+ font-weight: normal;
+ font-style: normal;
+ display: inline-block;
+ text-decoration: inherit;
+ content: "\f10d";
+ left: 8px;
+ top: 5px;
+ position: absolute;
+ font-size: 20px;
+ @include opacity(0.6);
+ }
+}
+pre {
+ border: none;
+ background-color: #f7f7f7;
+ margin: 5px 0;
+ .current--user & {
+ background: #fff;
+ }
+ code {
+ color: #c7254e;
+ }
+}
+code {
+ background: #fff;
+}
diff --git a/web/sass-files/sass/partials/_mentions.scss b/web/sass-files/sass/partials/_mentions.scss
index aa893c535..48746ba01 100644
--- a/web/sass-files/sass/partials/_mentions.scss
+++ b/web/sass-files/sass/partials/_mentions.scss
@@ -63,10 +63,11 @@
padding-left: 10px;
}
-.mention-highlight {
- background-color:#fff2bb;
+.mention-link {
+ color: $primary-color;
}
-.mention-link {
- color:$primary-color;
+.mention-highlight {
+ background-color:#fff2bb;
+ color: #333;
} \ No newline at end of file
diff --git a/web/sass-files/sass/partials/_modal.scss b/web/sass-files/sass/partials/_modal.scss
index a046cd904..e4e8b20b6 100644
--- a/web/sass-files/sass/partials/_modal.scss
+++ b/web/sass-files/sass/partials/_modal.scss
@@ -3,11 +3,36 @@
}
.modal {
width: 100%;
+ color: #333;
&.image_modal {
.modal-backdrop.in {
@include opacity(0.7);
}
}
+ a, a:focus, a:hover {
+ color: #2389D7;
+ &.text-danger {
+ color: #a94442;
+ }
+ }
+ .custom-textarea {
+ color: inherit;
+ border-color: #ccc;
+ &:focus {
+ border-color: #ccc;
+ box-shadow: none;
+ }
+ }
+ .btn {
+ font-size: 13px;
+ &.btn-primary {
+ background: #4285f4;
+ &:hover, &:focus, &:active {
+ background: $primary-color--hover;
+ color: #fff;
+ }
+ }
+ }
.info__label {
font-weight: 600;
text-align: right;
@@ -171,16 +196,13 @@
position: relative;
max-width: 90%;
min-height: 100px;
- min-width: 320px;
+ min-width: 240px;
@include border-radius(3px);
display: table;
margin: 0 auto;
&:hover {
@include border-radius(3px 3px 0 0);
}
- &:hover .modal-close {
- @include opacity(1);
- }
&.default {
width: 100%;
height: 80%;
@@ -194,8 +216,15 @@
right: -13px;
top: -13px;
@include opacity(0);
+ -webkit-transition: opacity 0.6s;
+ -moz-transition: opacity 0.6s;
+ -o-transition: opacity 0.6s;
+ transition: opacity 0.6s;
cursor: pointer;
z-index: 9999;
+ &.modal-close--show {
+ @include opacity(1);
+ }
}
> a {
background: #FFF;
@@ -207,7 +236,7 @@
max-height: 100%;
}
}
- .image-content {
+ .modal-content{
box-shadow: none;
background: rgba(0, 0, 0, 0);
width: 100%;
@@ -291,6 +320,7 @@
}
}
+
// Invite New Member
.invite {
margin-right: 40px;
@@ -305,4 +335,4 @@
padding-left: 0;
}
}
-} \ No newline at end of file
+}
diff --git a/web/sass-files/sass/partials/_post.scss b/web/sass-files/sass/partials/_post.scss
index 6940cf2fb..7532875d6 100644
--- a/web/sass-files/sass/partials/_post.scss
+++ b/web/sass-files/sass/partials/_post.scss
@@ -2,13 +2,17 @@
white-space:pre-wrap;
word-wrap:break-word;
background:transparent;
- border:1px solid #ccc !important;
+ border:1px solid #ccc;
position:absolute;
top:0px;
height:auto;
resize: none;
line-height:20px;
min-height:36px;
+ &:focus {
+ border-color: #ccc;
+ box-shadow: none;
+ }
}
.bad-connection {
@@ -225,17 +229,17 @@ body.ios {
right: 0;
position: absolute;
top: 1px;
- color: #999;
+ color: #444;
+ @include opacity(0.5);
@include single-transition(all, 0.15s);
font-size: 16px;
padding: 7px 9px 6px;
&:hover, &:active {
- color: #444;
+ @include opacity(0.9);
box-shadow: none;
}
}
textarea {
- border: none;
box-shadow: none;
}
}
@@ -253,7 +257,7 @@ body.ios {
line-height: 18px;
display: inline-block;
font-size: 13px;
- color: #777;
+ @include opacity(0.6);
}
}
}
@@ -275,7 +279,7 @@ body.ios {
&.current--user {
.post-body {
@include border-radius(4px);
- background: #f5f5f5;
+ background: rgba(#000, 0.05);
}
}
&.post--comment {
diff --git a/web/sass-files/sass/partials/_search.scss b/web/sass-files/sass/partials/_search.scss
index 9ae41ebb0..9abdd40da 100644
--- a/web/sass-files/sass/partials/_search.scss
+++ b/web/sass-files/sass/partials/_search.scss
@@ -107,4 +107,5 @@
.search-highlight.theme, .search-highlight {
background-color: #FFF2BB;
+ color: #333;
}
diff --git a/web/sass-files/sass/partials/_settings.scss b/web/sass-files/sass/partials/_settings.scss
index 2b59a943b..3aab05d70 100644
--- a/web/sass-files/sass/partials/_settings.scss
+++ b/web/sass-files/sass/partials/_settings.scss
@@ -32,6 +32,7 @@
}
.settings-table {
display: table;
+ table-layout: fixed;
width: 100%;
> div {
display: table-cell;
@@ -79,6 +80,36 @@
}
}
+ .appearance-section {
+ .premade-themes {
+ .theme-label {
+ font-weight: 400;
+ margin-top: 5px;
+ }
+ img {
+ border: 3px solid transparent;
+ }
+ .active {
+ img {
+ border-color: $primary-color;
+ }
+ }
+ }
+ .custom-label {
+ font-weight: normal;
+ font-size: 13px;
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-bottom: 0;
+ }
+ .radio {
+ label {
+ font-weight: 600;
+ }
+ }
+ }
+
.section-title {
margin-bottom: 5px;
font-weight: 600;
@@ -95,6 +126,10 @@
}
}
+ .font--small {
+ font-size: 13px;
+ }
+
.section-describe {
color:grey;
}
@@ -125,8 +160,18 @@
.has-error {
color: #a94442;
}
+ .padding-top {
+ padding-top: 7px;
+ &.x2 {
+ padding-top: 14px;
+ }
+ }
.control-label {
color: #555;
+ font-weight: 600;
+ &.text-left {
+ text-align: left;
+ }
}
hr {
border-color: #ccc;
diff --git a/web/sass-files/sass/partials/_sidebar--left.scss b/web/sass-files/sass/partials/_sidebar--left.scss
index 94583b153..6a418e270 100644
--- a/web/sass-files/sass/partials/_sidebar--left.scss
+++ b/web/sass-files/sass/partials/_sidebar--left.scss
@@ -16,6 +16,12 @@
overflow-y: auto;
max-width: 200px;
width: 200px;
+ a {
+ color: #262626 !important;
+ &:hover, &:focus {
+ background: #f5f5f5 !important;
+ }
+ }
}
.search__form {
margin: 0;
diff --git a/web/sass-files/sass/partials/_sidebar--right.scss b/web/sass-files/sass/partials/_sidebar--right.scss
index d02a92448..b37dbf421 100644
--- a/web/sass-files/sass/partials/_sidebar--right.scss
+++ b/web/sass-files/sass/partials/_sidebar--right.scss
@@ -51,9 +51,10 @@
margin: 11px 0 0 0;
width: 22px;
height: 22px;
- background: url("../images/closeSidebar.png");
- @include background-size(100% 100%);
opacity: 0.5;
+ font-size: 22px;
+ line-height: 0;
+ background: none;
float: right;
outline: none;
border: none;
@@ -61,11 +62,15 @@
&:hover, &:active {
opacity: 0.8;
}
+ i {
+ position: relative;
+ top: -2px;
+ }
}
.sidebar--right__header {
font-size: 1em;
text-transform: uppercase;
- color: #444;
+ color: inherit;
height: 44px;
padding: 0 1em;
line-height: 44px;
diff --git a/web/sass-files/sass/partials/_videos.scss b/web/sass-files/sass/partials/_videos.scss
index de18aa08a..9e1ce29b7 100644
--- a/web/sass-files/sass/partials/_videos.scss
+++ b/web/sass-files/sass/partials/_videos.scss
@@ -1,6 +1,7 @@
.video-div {
position:relative;
max-width: 480px;
+ margin-bottom: 8px;
.video-thumbnail {
max-width: 100%;
height: auto;
@@ -19,18 +20,15 @@
}
.video-type {
- color:grey;
+ @include opacity(0.8);
font-size:15px;
- font-weight:200;
margin:0px;
padding:0px;
}
.video-uploader {
- font-size:15px;
- margin-top:3px;
- margin-bottom:0px;
- padding:0px;
+ font-size: 13px;
+ margin: 0 0 15px;
}
.video-title {
diff --git a/web/sass-files/sass/styles.scss b/web/sass-files/sass/styles.scss
index de1db57e8..e704536a8 100644
--- a/web/sass-files/sass/styles.scss
+++ b/web/sass-files/sass/styles.scss
@@ -10,6 +10,7 @@
@import "partials/perfect-scrollbar";
@import "partials/font-awesome";
@import "partials/base";
+@import "partials/colorpicker";
// Channel Css
@import "partials/headers";
@@ -36,6 +37,7 @@
@import "partials/error-bar";
@import "partials/loading";
@import "partials/get-link";
+@import "partials/markdown";
// Responsive Css
@import "partials/responsive";
diff --git a/web/static/css/bootstrap-colorpicker.min.css b/web/static/css/bootstrap-colorpicker.min.css
new file mode 100755
index 000000000..5656e768f
--- /dev/null
+++ b/web/static/css/bootstrap-colorpicker.min.css
@@ -0,0 +1,9 @@
+/*!
+ * Bootstrap Colorpicker
+ * http://mjolnic.github.io/bootstrap-colorpicker/
+ *
+ * Originally written by (c) 2012 Stefan Petre
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0.txt
+ *
+ */.colorpicker-saturation{float:left;width:100px;height:100px;cursor:crosshair;background-image:url("../images/bootstrap-colorpicker/saturation.png")}.colorpicker-saturation i{position:absolute;top:0;left:0;display:block;width:5px;height:5px;margin:-4px 0 0 -4px;border:1px solid #000;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.colorpicker-saturation i b{display:block;width:5px;height:5px;border:1px solid #fff;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.colorpicker-hue,.colorpicker-alpha{float:left;width:15px;height:100px;margin-bottom:4px;margin-left:4px;cursor:row-resize}.colorpicker-hue i,.colorpicker-alpha i{position:absolute;top:0;left:0;display:block;width:100%;height:1px;margin-top:-1px;background:#000;border-top:1px solid #fff}.colorpicker-hue{background-image:url("../images/bootstrap-colorpicker/hue.png")}.colorpicker-alpha{display:none;background-image:url("../images/bootstrap-colorpicker/alpha.png")}.colorpicker-saturation,.colorpicker-hue,.colorpicker-alpha{background-size:contain}.colorpicker{top:0;left:0;z-index:2500;min-width:130px;padding:4px;margin-top:1px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1}.colorpicker:before,.colorpicker:after{display:table;line-height:0;content:""}.colorpicker:after{clear:both}.colorpicker:before{position:absolute;top:-7px;left:6px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.colorpicker:after{position:absolute;top:-6px;left:7px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.colorpicker div{position:relative}.colorpicker.colorpicker-with-alpha{min-width:140px}.colorpicker.colorpicker-with-alpha .colorpicker-alpha{display:block}.colorpicker-color{height:10px;margin-top:5px;clear:both;background-image:url("../images/bootstrap-colorpicker/alpha.png");background-position:0 100%}.colorpicker-color div{height:10px}.colorpicker-selectors{display:none;height:10px;margin-top:5px;clear:both}.colorpicker-selectors i{float:left;width:10px;height:10px;cursor:pointer}.colorpicker-selectors i+i{margin-left:3px}.colorpicker-element .input-group-addon i,.colorpicker-element .add-on i{display:inline-block;width:16px;height:16px;vertical-align:text-top;cursor:pointer}.colorpicker.colorpicker-inline{position:relative;z-index:auto;display:inline-block;float:none}.colorpicker.colorpicker-horizontal{width:110px;height:auto;min-width:110px}.colorpicker.colorpicker-horizontal .colorpicker-saturation{margin-bottom:4px}.colorpicker.colorpicker-horizontal .colorpicker-color{width:100px}.colorpicker.colorpicker-horizontal .colorpicker-hue,.colorpicker.colorpicker-horizontal .colorpicker-alpha{float:left;width:100px;height:15px;margin-bottom:4px;margin-left:0;cursor:col-resize}.colorpicker.colorpicker-horizontal .colorpicker-hue i,.colorpicker.colorpicker-horizontal .colorpicker-alpha i{position:absolute;top:0;left:0;display:block;width:1px;height:15px;margin-top:0;background:#fff;border:0}.colorpicker.colorpicker-horizontal .colorpicker-hue{background-image:url("../images/bootstrap-colorpicker/hue-horizontal.png")}.colorpicker.colorpicker-horizontal .colorpicker-alpha{background-image:url("../images/bootstrap-colorpicker/alpha-horizontal.png")}.colorpicker.colorpicker-hidden{display:none}.colorpicker.colorpicker-visible{display:block}.colorpicker-inline.colorpicker-visible{display:inline-block}.colorpicker-right:before{right:6px;left:auto}.colorpicker-right:after{right:7px;left:auto}
diff --git a/web/static/images/bootstrap-colorpicker/alpha-horizontal.png b/web/static/images/bootstrap-colorpicker/alpha-horizontal.png
new file mode 100755
index 000000000..d0a65c08b
--- /dev/null
+++ b/web/static/images/bootstrap-colorpicker/alpha-horizontal.png
Binary files differ
diff --git a/web/static/images/bootstrap-colorpicker/alpha.png b/web/static/images/bootstrap-colorpicker/alpha.png
new file mode 100755
index 000000000..38043f1c8
--- /dev/null
+++ b/web/static/images/bootstrap-colorpicker/alpha.png
Binary files differ
diff --git a/web/static/images/bootstrap-colorpicker/hue-horizontal.png b/web/static/images/bootstrap-colorpicker/hue-horizontal.png
new file mode 100755
index 000000000..a0d9add8e
--- /dev/null
+++ b/web/static/images/bootstrap-colorpicker/hue-horizontal.png
Binary files differ
diff --git a/web/static/images/bootstrap-colorpicker/hue.png b/web/static/images/bootstrap-colorpicker/hue.png
new file mode 100755
index 000000000..d89560e99
--- /dev/null
+++ b/web/static/images/bootstrap-colorpicker/hue.png
Binary files differ
diff --git a/web/static/images/bootstrap-colorpicker/saturation.png b/web/static/images/bootstrap-colorpicker/saturation.png
new file mode 100755
index 000000000..594ae50ed
--- /dev/null
+++ b/web/static/images/bootstrap-colorpicker/saturation.png
Binary files differ
diff --git a/web/static/images/themes/mattermost dark.png b/web/static/images/themes/mattermost dark.png
new file mode 100644
index 000000000..832f64d2e
--- /dev/null
+++ b/web/static/images/themes/mattermost dark.png
Binary files differ
diff --git a/web/static/images/themes/mattermost.png b/web/static/images/themes/mattermost.png
new file mode 100644
index 000000000..4a321adcb
--- /dev/null
+++ b/web/static/images/themes/mattermost.png
Binary files differ
diff --git a/web/static/images/themes/organization.png b/web/static/images/themes/organization.png
new file mode 100644
index 000000000..1a38bfb34
--- /dev/null
+++ b/web/static/images/themes/organization.png
Binary files differ
diff --git a/web/static/images/themes/slack.png b/web/static/images/themes/slack.png
new file mode 100644
index 000000000..dc70c7dc2
--- /dev/null
+++ b/web/static/images/themes/slack.png
Binary files differ
diff --git a/web/static/images/themes/windows dark.png b/web/static/images/themes/windows dark.png
new file mode 100644
index 000000000..d65304820
--- /dev/null
+++ b/web/static/images/themes/windows dark.png
Binary files differ
diff --git a/web/static/js/bootstrap-colorpicker.min.js b/web/static/js/bootstrap-colorpicker.min.js
new file mode 100755
index 000000000..05c0e0744
--- /dev/null
+++ b/web/static/js/bootstrap-colorpicker.min.js
@@ -0,0 +1 @@
+!function(a){"use strict";"object"==typeof exports?module.exports=a(window.jQuery):"function"==typeof define&&define.amd?define(["jquery"],a):window.jQuery&&!window.jQuery.fn.colorpicker&&a(window.jQuery)}(function(a){"use strict";var b=function(b,c){this.value={h:0,s:0,b:0,a:1},this.origFormat=null,c&&a.extend(this.colors,c),b&&(void 0!==b.toLowerCase?(b+="",this.setColor(b)):void 0!==b.h&&(this.value=b))};b.prototype={constructor:b,colors:{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",transparent:"transparent"},_sanitizeNumber:function(a){return"number"==typeof a?a:isNaN(a)||null===a||""===a||void 0===a?1:void 0!==a.toLowerCase?parseFloat(a):1},isTransparent:function(a){return a?(a=a.toLowerCase().trim(),"transparent"===a||a.match(/#?00000000/)||a.match(/(rgba|hsla)\(0,0,0,0?\.?0\)/)):!1},rgbaIsTransparent:function(a){return 0===a.r&&0===a.g&&0===a.b&&0===a.a},setColor:function(a){a=a.toLowerCase().trim(),a&&(this.isTransparent(a)?this.value={h:0,s:0,b:0,a:0}:this.value=this.stringToHSB(a)||{h:0,s:0,b:0,a:1})},stringToHSB:function(b){b=b.toLowerCase();var c;"undefined"!=typeof this.colors[b]&&(b=this.colors[b],c="alias");var d=this,e=!1;return a.each(this.stringParsers,function(a,f){var g=f.re.exec(b),h=g&&f.parse.apply(d,[g]),i=c||f.format||"rgba";return h?(e=i.match(/hsla?/)?d.RGBtoHSB.apply(d,d.HSLtoRGB.apply(d,h)):d.RGBtoHSB.apply(d,h),d.origFormat=i,!1):!0}),e},setHue:function(a){this.value.h=1-a},setSaturation:function(a){this.value.s=a},setBrightness:function(a){this.value.b=1-a},setAlpha:function(a){this.value.a=parseInt(100*(1-a),10)/100},toRGB:function(a,b,c,d){a||(a=this.value.h,b=this.value.s,c=this.value.b),a*=360;var e,f,g,h,i;return a=a%360/60,i=c*b,h=i*(1-Math.abs(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],{r:Math.round(255*e),g:Math.round(255*f),b:Math.round(255*g),a:d||this.value.a}},toHex:function(a,b,c,d){var e=this.toRGB(a,b,c,d);return this.rgbaIsTransparent(e)?"transparent":"#"+(1<<24|parseInt(e.r)<<16|parseInt(e.g)<<8|parseInt(e.b)).toString(16).substr(1)},toHSL:function(a,b,c,d){a=a||this.value.h,b=b||this.value.s,c=c||this.value.b,d=d||this.value.a;var e=a,f=(2-b)*c,g=b*c;return g/=f>0&&1>=f?f:2-f,f/=2,g>1&&(g=1),{h:isNaN(e)?0:e,s:isNaN(g)?0:g,l:isNaN(f)?0:f,a:isNaN(d)?0:d}},toAlias:function(a,b,c,d){var e=this.toHex(a,b,c,d);for(var f in this.colors)if(this.colors[f]===e)return f;return!1},RGBtoHSB:function(a,b,c,d){a/=255,b/=255,c/=255;var e,f,g,h;return g=Math.max(a,b,c),h=g-Math.min(a,b,c),e=0===h?null:g===a?(b-c)/h:g===b?(c-a)/h+2:(a-b)/h+4,e=(e+360)%6*60/360,f=0===h?0:h/g,{h:this._sanitizeNumber(e),s:f,b:g,a:this._sanitizeNumber(d)}},HueToRGB:function(a,b,c){return 0>c?c+=1:c>1&&(c-=1),1>6*c?a+(b-a)*c*6:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a},HSLtoRGB:function(a,b,c,d){0>b&&(b=0);var e;e=.5>=c?c*(1+b):c+b-c*b;var f=2*c-e,g=a+1/3,h=a,i=a-1/3,j=Math.round(255*this.HueToRGB(f,e,g)),k=Math.round(255*this.HueToRGB(f,e,h)),l=Math.round(255*this.HueToRGB(f,e,i));return[j,k,l,this._sanitizeNumber(d)]},toString:function(a){a=a||"rgba";var b=!1;switch(a){case"rgb":return b=this.toRGB(),this.rgbaIsTransparent(b)?"transparent":"rgb("+b.r+","+b.g+","+b.b+")";case"rgba":return b=this.toRGB(),"rgba("+b.r+","+b.g+","+b.b+","+b.a+")";case"hsl":return b=this.toHSL(),"hsl("+Math.round(360*b.h)+","+Math.round(100*b.s)+"%,"+Math.round(100*b.l)+"%)";case"hsla":return b=this.toHSL(),"hsla("+Math.round(360*b.h)+","+Math.round(100*b.s)+"%,"+Math.round(100*b.l)+"%,"+b.a+")";case"hex":return this.toHex();case"alias":return this.toAlias()||this.toHex();default:return b}},stringParsers:[{re:/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*?\)/,format:"rgb",parse:function(a){return[a[1],a[2],a[3],1]}},{re:/rgb\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*?\)/,format:"rgb",parse:function(a){return[2.55*a[1],2.55*a[2],2.55*a[3],1]}},{re:/rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,format:"rgba",parse:function(a){return[a[1],a[2],a[3],a[4]]}},{re:/rgba\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,format:"rgba",parse:function(a){return[2.55*a[1],2.55*a[2],2.55*a[3],a[4]]}},{re:/hsl\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*?\)/,format:"hsl",parse:function(a){return[a[1]/360,a[2]/100,a[3]/100,a[4]]}},{re:/hsla\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,format:"hsla",parse:function(a){return[a[1]/360,a[2]/100,a[3]/100,a[4]]}},{re:/#?([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,format:"hex",parse:function(a){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16),1]}},{re:/#?([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/,format:"hex",parse:function(a){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16),1]}}],colorNameToHex:function(a){return"undefined"!=typeof this.colors[a.toLowerCase()]?this.colors[a.toLowerCase()]:!1}};var c={horizontal:!1,inline:!1,color:!1,format:!1,input:"input",container:!1,component:".add-on, .input-group-addon",sliders:{saturation:{maxLeft:100,maxTop:100,callLeft:"setSaturation",callTop:"setBrightness"},hue:{maxLeft:0,maxTop:100,callLeft:!1,callTop:"setHue"},alpha:{maxLeft:0,maxTop:100,callLeft:!1,callTop:"setAlpha"}},slidersHorz:{saturation:{maxLeft:100,maxTop:100,callLeft:"setSaturation",callTop:"setBrightness"},hue:{maxLeft:100,maxTop:0,callLeft:"setHue",callTop:!1},alpha:{maxLeft:100,maxTop:0,callLeft:"setAlpha",callTop:!1}},template:'<div class="colorpicker dropdown-menu"><div class="colorpicker-saturation"><i><b></b></i></div><div class="colorpicker-hue"><i></i></div><div class="colorpicker-alpha"><i></i></div><div class="colorpicker-color"><div /></div><div class="colorpicker-selectors"></div></div>',align:"right",customClass:null,colorSelectors:null},d=function(d,e){if(this.element=a(d).addClass("colorpicker-element"),this.options=a.extend(!0,{},c,this.element.data(),e),this.component=this.options.component,this.component=this.component!==!1?this.element.find(this.component):!1,this.component&&0===this.component.length&&(this.component=!1),this.container=this.options.container===!0?this.element:this.options.container,this.container=this.container!==!1?a(this.container):!1,this.input=this.element.is("input")?this.element:this.options.input?this.element.find(this.options.input):!1,this.input&&0===this.input.length&&(this.input=!1),this.color=new b(this.options.color!==!1?this.options.color:this.getValue(),this.options.colorSelectors),this.format=this.options.format!==!1?this.options.format:this.color.origFormat,this.picker=a(this.options.template),this.options.customClass&&this.picker.addClass(this.options.customClass),this.options.inline?this.picker.addClass("colorpicker-inline colorpicker-visible"):this.picker.addClass("colorpicker-hidden"),this.options.horizontal&&this.picker.addClass("colorpicker-horizontal"),("rgba"===this.format||"hsla"===this.format||this.options.format===!1)&&this.picker.addClass("colorpicker-with-alpha"),"right"===this.options.align&&this.picker.addClass("colorpicker-right"),this.options.colorSelectors){var f=this;a.each(this.options.colorSelectors,function(b,c){var d=a("<i />").css("background-color",c).data("class",b);d.click(function(){f.setValue(a(this).css("background-color"))}),f.picker.find(".colorpicker-selectors").append(d)}),this.picker.find(".colorpicker-selectors").show()}this.picker.on("mousedown.colorpicker touchstart.colorpicker",a.proxy(this.mousedown,this)),this.picker.appendTo(this.container?this.container:a("body")),this.input!==!1&&(this.input.on({"keyup.colorpicker":a.proxy(this.keyup,this)}),this.input.on({"change.colorpicker":a.proxy(this.change,this)}),this.component===!1&&this.element.on({"focus.colorpicker":a.proxy(this.show,this)}),this.options.inline===!1&&this.element.on({"focusout.colorpicker":a.proxy(this.hide,this)})),this.component!==!1&&this.component.on({"click.colorpicker":a.proxy(this.show,this)}),this.input===!1&&this.component===!1&&this.element.on({"click.colorpicker":a.proxy(this.show,this)}),this.input!==!1&&this.component!==!1&&"color"===this.input.attr("type")&&this.input.on({"click.colorpicker":a.proxy(this.show,this),"focus.colorpicker":a.proxy(this.show,this)}),this.update(),a(a.proxy(function(){this.element.trigger("create")},this))};d.Color=b,d.prototype={constructor:d,destroy:function(){this.picker.remove(),this.element.removeData("colorpicker").off(".colorpicker"),this.input!==!1&&this.input.off(".colorpicker"),this.component!==!1&&this.component.off(".colorpicker"),this.element.removeClass("colorpicker-element"),this.element.trigger({type:"destroy"})},reposition:function(){if(this.options.inline!==!1||this.options.container)return!1;var a=this.container&&this.container[0]!==document.body?"position":"offset",b=this.component||this.element,c=b[a]();"right"===this.options.align&&(c.left-=this.picker.outerWidth()-b.outerWidth()),this.picker.css({top:c.top+b.outerHeight(),left:c.left})},show:function(b){return this.isDisabled()?!1:(this.picker.addClass("colorpicker-visible").removeClass("colorpicker-hidden"),this.reposition(),a(window).on("resize.colorpicker",a.proxy(this.reposition,this)),!b||this.hasInput()&&"color"!==this.input.attr("type")||b.stopPropagation&&b.preventDefault&&(b.stopPropagation(),b.preventDefault()),this.options.inline===!1&&a(window.document).on({"mousedown.colorpicker":a.proxy(this.hide,this)}),void this.element.trigger({type:"showPicker",color:this.color}))},hide:function(){this.picker.addClass("colorpicker-hidden").removeClass("colorpicker-visible"),a(window).off("resize.colorpicker",this.reposition),a(document).off({"mousedown.colorpicker":this.hide}),this.update(),this.element.trigger({type:"hidePicker",color:this.color})},updateData:function(a){return a=a||this.color.toString(this.format),this.element.data("color",a),a},updateInput:function(a){if(a=a||this.color.toString(this.format),this.input!==!1){if(this.options.colorSelectors){var c=new b(a,this.options.colorSelectors),d=c.toAlias();"undefined"!=typeof this.options.colorSelectors[d]&&(a=d)}this.input.prop("value",a)}return a},updatePicker:function(a){void 0!==a&&(this.color=new b(a,this.options.colorSelectors));var c=this.options.horizontal===!1?this.options.sliders:this.options.slidersHorz,d=this.picker.find("i");return 0!==d.length?(this.options.horizontal===!1?(c=this.options.sliders,d.eq(1).css("top",c.hue.maxTop*(1-this.color.value.h)).end().eq(2).css("top",c.alpha.maxTop*(1-this.color.value.a))):(c=this.options.slidersHorz,d.eq(1).css("left",c.hue.maxLeft*(1-this.color.value.h)).end().eq(2).css("left",c.alpha.maxLeft*(1-this.color.value.a))),d.eq(0).css({top:c.saturation.maxTop-this.color.value.b*c.saturation.maxTop,left:this.color.value.s*c.saturation.maxLeft}),this.picker.find(".colorpicker-saturation").css("backgroundColor",this.color.toHex(this.color.value.h,1,1,1)),this.picker.find(".colorpicker-alpha").css("backgroundColor",this.color.toHex()),this.picker.find(".colorpicker-color, .colorpicker-color div").css("backgroundColor",this.color.toString(this.format)),a):void 0},updateComponent:function(a){if(a=a||this.color.toString(this.format),this.component!==!1){var b=this.component.find("i").eq(0);b.length>0?b.css({backgroundColor:a}):this.component.css({backgroundColor:a})}return a},update:function(a){var b;return(this.getValue(!1)!==!1||a===!0)&&(b=this.updateComponent(),this.updateInput(b),this.updateData(b),this.updatePicker()),b},setValue:function(a){this.color=new b(a,this.options.colorSelectors),this.update(!0),this.element.trigger({type:"changeColor",color:this.color,value:a})},getValue:function(a){a=void 0===a?"#000000":a;var b;return b=this.hasInput()?this.input.val():this.element.data("color"),(void 0===b||""===b||null===b)&&(b=a),b},hasInput:function(){return this.input!==!1},isDisabled:function(){return this.hasInput()?this.input.prop("disabled")===!0:!1},disable:function(){return this.hasInput()?(this.input.prop("disabled",!0),this.element.trigger({type:"disable",color:this.color,value:this.getValue()}),!0):!1},enable:function(){return this.hasInput()?(this.input.prop("disabled",!1),this.element.trigger({type:"enable",color:this.color,value:this.getValue()}),!0):!1},currentSlider:null,mousePointer:{left:0,top:0},mousedown:function(b){b.pageX||b.pageY||!b.originalEvent||(b.pageX=b.originalEvent.touches[0].pageX,b.pageY=b.originalEvent.touches[0].pageY),b.stopPropagation(),b.preventDefault();var c=a(b.target),d=c.closest("div"),e=this.options.horizontal?this.options.slidersHorz:this.options.sliders;if(!d.is(".colorpicker")){if(d.is(".colorpicker-saturation"))this.currentSlider=a.extend({},e.saturation);else if(d.is(".colorpicker-hue"))this.currentSlider=a.extend({},e.hue);else{if(!d.is(".colorpicker-alpha"))return!1;this.currentSlider=a.extend({},e.alpha)}var f=d.offset();this.currentSlider.guide=d.find("i")[0].style,this.currentSlider.left=b.pageX-f.left,this.currentSlider.top=b.pageY-f.top,this.mousePointer={left:b.pageX,top:b.pageY},a(document).on({"mousemove.colorpicker":a.proxy(this.mousemove,this),"touchmove.colorpicker":a.proxy(this.mousemove,this),"mouseup.colorpicker":a.proxy(this.mouseup,this),"touchend.colorpicker":a.proxy(this.mouseup,this)}).trigger("mousemove")}return!1},mousemove:function(a){a.pageX||a.pageY||!a.originalEvent||(a.pageX=a.originalEvent.touches[0].pageX,a.pageY=a.originalEvent.touches[0].pageY),a.stopPropagation(),a.preventDefault();var b=Math.max(0,Math.min(this.currentSlider.maxLeft,this.currentSlider.left+((a.pageX||this.mousePointer.left)-this.mousePointer.left))),c=Math.max(0,Math.min(this.currentSlider.maxTop,this.currentSlider.top+((a.pageY||this.mousePointer.top)-this.mousePointer.top)));return this.currentSlider.guide.left=b+"px",this.currentSlider.guide.top=c+"px",this.currentSlider.callLeft&&this.color[this.currentSlider.callLeft].call(this.color,b/this.currentSlider.maxLeft),this.currentSlider.callTop&&this.color[this.currentSlider.callTop].call(this.color,c/this.currentSlider.maxTop),"setAlpha"===this.currentSlider.callTop&&this.options.format===!1&&(1!==this.color.value.a?(this.format="rgba",this.color.origFormat="rgba"):(this.format="hex",this.color.origFormat="hex")),this.update(!0),this.element.trigger({type:"changeColor",color:this.color}),!1},mouseup:function(b){return b.stopPropagation(),b.preventDefault(),a(document).off({"mousemove.colorpicker":this.mousemove,"touchmove.colorpicker":this.mousemove,"mouseup.colorpicker":this.mouseup,"touchend.colorpicker":this.mouseup}),!1},change:function(a){this.keyup(a)},keyup:function(a){38===a.keyCode?(this.color.value.a<1&&(this.color.value.a=Math.round(100*(this.color.value.a+.01))/100),this.update(!0)):40===a.keyCode?(this.color.value.a>0&&(this.color.value.a=Math.round(100*(this.color.value.a-.01))/100),this.update(!0)):(this.color=new b(this.input.val(),this.options.colorSelectors),this.color.origFormat&&this.options.format===!1&&(this.format=this.color.origFormat),this.getValue(!1)!==!1&&(this.updateData(),this.updateComponent(),this.updatePicker())),this.element.trigger({type:"changeColor",color:this.color,value:this.input.val()})}},a.colorpicker=d,a.fn.colorpicker=function(b){var c,e=arguments,f=this.each(function(){var f=a(this),g=f.data("colorpicker"),h="object"==typeof b?b:{};g||"string"==typeof b?"string"==typeof b&&(c=g[b].apply(g,Array.prototype.slice.call(e,1))):f.data("colorpicker",new d(this,h))});return"getValue"===b?c:f},a.fn.colorpicker.constructor=d}); \ No newline at end of file
diff --git a/web/static/js/emojify.min.js b/web/static/js/emojify.min.js
deleted file mode 100755
index 4fedf3205..000000000
--- a/web/static/js/emojify.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! emojify.js - v1.0.5 -
- * Copyright (c) Hassan Khan 2015
- */
-!function(e,a){"use strict";"function"==typeof define&&define.amd?define([],a):"object"==typeof exports?module.exports=a():e.emojify=a()}(this,function(){"use strict";var e=function(){function e(){var e={named:/:([a-z0-9A-Z_-]+):/,smile:/:-?\)/g,open_mouth:/:o/gi,scream:/:-o/gi,smirk:/[:;]-?]/g,grinning:/[:;]-?d/gi,stuck_out_tongue_closed_eyes:/x-d/gi,stuck_out_tongue_winking_eye:/[:;]-?p/gi,rage:/:-?[\[@]/g,frowning:/:-?\(/g,sob:/:['’]-?\(|:&#x27;\(/g,kissing_heart:/:-?\*/g,wink:/;-?\)/g,pensive:/:-?\//g,confounded:/:-?s/gi,flushed:/:-?\|/g,relaxed:/:-?\$/g,mask:/:-x/gi,heart:/<3|&lt;3/g,broken_heart:/<\/3|&lt;&#x2F;3/g,thumbsup:/:\+1:/g,thumbsdown:/:\-1:/g};return d.ignore_emoticons&&(e={named:/:([a-z0-9A-Z_-]+):/,thumbsup:/:\+1:/g,thumbsdown:/:\-1:/g}),Object.keys(e).map(function(a){return[e[a],a]})}function a(){var e=_.map(function(e){var a=e[0],o=a.source||a;return o=o.replace(/(^|[^\[])\^/g,"$1"),"("+o+")"}).join("|");return new RegExp(e,"gi")}function o(e){return" "===e||" "===e||"\r"===e||"\n"===e||""===e||e===String.fromCharCode(160)}function r(e){var a=null;if(e.replacer)a=e.replacer.apply({config:d},[":"+e.emojiName+":",e.emojiName]);else{var o=d.tag_type||h[d.mode];a=e.win.document.createElement(o),"img"!==o?a.setAttribute("class","emoji emoji-"+e.emojiName):(a.setAttribute("align","absmiddle"),a.setAttribute("alt",":"+e.emojiName+":"),a.setAttribute("class","emoji"),a.setAttribute("src",d.img_dir+"/"+e.emojiName+".png")),a.setAttribute("title",":"+e.emojiName+":")}e.node.splitText(e.match.index),e.node.nextSibling.nodeValue=e.node.nextSibling.nodeValue.substr(e.match[0].length,e.node.nextSibling.nodeValue.length),a.appendChild(e.node.splitText(e.match.index)),e.node.parentNode.insertBefore(a,e.node.nextSibling)}function t(e){if(e[1]&&e[2]){var a=e[2];if(m[a])return a}else for(var o=3;o<e.length-1;o++)if(e[o])return _[o-2][1]}function i(e,a){var o=this.config.tag_type||h[this.config.mode];return"img"!==o?"<"+o+" class='emoji emoji-"+a+"' title=':"+a+":'></"+o+">":"<img align='absmiddle' alt=':"+a+":' class='emoji' src='"+this.config.img_dir+"/"+a+".png' title=':"+a+":' />"}function n(){this.lastEmojiTerminatedAt=-1}function s(o,r){if(!o)return o;r||(r=i),_=e(),c=a();var t=new n;return o.replace(c,function(){var e=Array.prototype.slice.call(arguments,0,-2),a=arguments[arguments.length-2],o=arguments[arguments.length-1],i=t.validate(e,a,o);return i?r.apply({config:d},[arguments[0],i]):arguments[0]})}function l(o,i){"undefined"==typeof o&&(o=d.only_crawl_id?document.getElementById(d.only_crawl_id):document.body);var s=o.ownerDocument,l=s.defaultView||s.parentWindow,u=function(e,a){var o;if(e.hasChildNodes())for(o=e.firstChild;o;)a(o)&&u(o,a),o=o.nextSibling},g=function(e){for(var a,o=[],s=new n;null!==(a=c.exec(e.data));)s.validate(a,a.index,a.input)&&o.push(a);for(var _=o.length;_-->0;){var u=t(o[_]);r({node:e,match:o[_],emojiName:u,replacer:i,win:l})}};_=e(),c=a();var m=[],h=new RegExp(d.blacklist.elements.join("|"),"i"),p=new RegExp(d.blacklist.classes.join("|"),"i");if("undefined"!=typeof l.document.createTreeWalker)for(var b,f=l.document.createTreeWalker(o,l.NodeFilter.SHOW_TEXT|l.NodeFilter.SHOW_ELEMENT,function(e){return 1!==e.nodeType?l.NodeFilter.FILTER_ACCEPT:e.tagName.match(h)||"svg"===e.tagName||e.className.match(p)?l.NodeFilter.FILTER_REJECT:l.NodeFilter.FILTER_SKIP},!1);null!==(b=f.nextNode());)m.push(b);else u(o,function(e){return"undefined"!=typeof e.tagName&&e.tagName.match(h)||"undefined"!=typeof e.className&&e.className.match(p)?!1:1===e.nodeType?!0:(m.push(e),!0)});m.forEach(g)}var _,c,u="+1,-1,100,1234,8ball,a,ab,abc,abcd,accept,aerial_tramway,airplane,alarm_clock,alien,ambulance,anchor,angel,anger,angry,anguished,ant,apple,aquarius,aries,arrow_backward,arrow_double_down,arrow_double_up,arrow_down,arrow_down_small,arrow_forward,arrow_heading_down,arrow_heading_up,arrow_left,arrow_lower_left,arrow_lower_right,arrow_right,arrow_right_hook,arrow_up,arrow_up_down,arrow_up_small,arrow_upper_left,arrow_upper_right,arrows_clockwise,arrows_counterclockwise,art,articulated_lorry,astonished,atm,b,baby,baby_bottle,baby_chick,baby_symbol,back,baggage_claim,balloon,ballot_box_with_check,bamboo,banana,bangbang,bank,bar_chart,barber,baseball,basketball,bath,bathtub,battery,bear,bee,beer,beers,beetle,beginner,bell,bento,bicyclist,bike,bikini,bird,birthday,black_circle,black_joker,black_medium_small_square,black_medium_square,black_nib,black_small_square,black_square,black_square_button,blossom,blowfish,blue_book,blue_car,blue_heart,blush,boar,boat,bomb,book,bookmark,bookmark_tabs,books,boom,boot,bouquet,bow,bowling,bowtie,boy,bread,bride_with_veil,bridge_at_night,briefcase,broken_heart,bug,bulb,bullettrain_front,bullettrain_side,bus,busstop,bust_in_silhouette,busts_in_silhouette,cactus,cake,calendar,calling,camel,camera,cancer,candy,capital_abcd,capricorn,car,card_index,carousel_horse,cat,cat2,cd,chart,chart_with_downwards_trend,chart_with_upwards_trend,checkered_flag,cherries,cherry_blossom,chestnut,chicken,children_crossing,chocolate_bar,christmas_tree,church,cinema,circus_tent,city_sunrise,city_sunset,cl,clap,clapper,clipboard,clock1,clock10,clock1030,clock11,clock1130,clock12,clock1230,clock130,clock2,clock230,clock3,clock330,clock4,clock430,clock5,clock530,clock6,clock630,clock7,clock730,clock8,clock830,clock9,clock930,closed_book,closed_lock_with_key,closed_umbrella,cloud,clubs,cn,cocktail,coffee,cold_sweat,collision,computer,confetti_ball,confounded,confused,congratulations,construction,construction_worker,convenience_store,cookie,cool,cop,copyright,corn,couple,couple_with_heart,couplekiss,cow,cow2,credit_card,crescent_moon,crocodile,crossed_flags,crown,cry,crying_cat_face,crystal_ball,cupid,curly_loop,currency_exchange,curry,custard,customs,cyclone,dancer,dancers,dango,dart,dash,date,de,deciduous_tree,department_store,diamond_shape_with_a_dot_inside,diamonds,disappointed,disappointed_relieved,dizzy,dizzy_face,do_not_litter,dog,dog2,dollar,dolls,dolphin,donut,door,doughnut,dragon,dragon_face,dress,dromedary_camel,droplet,dvd,e-mail,ear,ear_of_rice,earth_africa,earth_americas,earth_asia,egg,eggplant,eight,eight_pointed_black_star,eight_spoked_asterisk,electric_plug,elephant,email,end,envelope,es,euro,european_castle,european_post_office,evergreen_tree,exclamation,expressionless,eyeglasses,eyes,facepunch,factory,fallen_leaf,family,fast_forward,fax,fearful,feelsgood,feet,ferris_wheel,file_folder,finnadie,fire,fire_engine,fireworks,first_quarter_moon,first_quarter_moon_with_face,fish,fish_cake,fishing_pole_and_fish,fist,five,flags,flashlight,floppy_disk,flower_playing_cards,flushed,foggy,football,fork_and_knife,fountain,four,four_leaf_clover,fr,free,fried_shrimp,fries,frog,frowning,fu,fuelpump,full_moon,full_moon_with_face,game_die,gb,gem,gemini,ghost,gift,gift_heart,girl,globe_with_meridians,goat,goberserk,godmode,golf,grapes,green_apple,green_book,green_heart,grey_exclamation,grey_question,grimacing,grin,grinning,guardsman,guitar,gun,haircut,hamburger,hammer,hamster,hand,handbag,hankey,hash,hatched_chick,hatching_chick,headphones,hear_no_evil,heart,heart_decoration,heart_eyes,heart_eyes_cat,heartbeat,heartpulse,hearts,heavy_check_mark,heavy_division_sign,heavy_dollar_sign,heavy_exclamation_mark,heavy_minus_sign,heavy_multiplication_x,heavy_plus_sign,helicopter,herb,hibiscus,high_brightness,high_heel,hocho,honey_pot,honeybee,horse,horse_racing,hospital,hotel,hotsprings,hourglass,hourglass_flowing_sand,house,house_with_garden,hurtrealbad,hushed,ice_cream,icecream,id,ideograph_advantage,imp,inbox_tray,incoming_envelope,information_desk_person,information_source,innocent,interrobang,iphone,it,izakaya_lantern,jack_o_lantern,japan,japanese_castle,japanese_goblin,japanese_ogre,jeans,joy,joy_cat,jp,key,keycap_ten,kimono,kiss,kissing,kissing_cat,kissing_closed_eyes,kissing_face,kissing_heart,kissing_smiling_eyes,koala,koko,kr,large_blue_circle,large_blue_diamond,large_orange_diamond,last_quarter_moon,last_quarter_moon_with_face,laughing,leaves,ledger,left_luggage,left_right_arrow,leftwards_arrow_with_hook,lemon,leo,leopard,libra,light_rail,link,lips,lipstick,lock,lock_with_ink_pen,lollipop,loop,loudspeaker,love_hotel,love_letter,low_brightness,m,mag,mag_right,mahjong,mailbox,mailbox_closed,mailbox_with_mail,mailbox_with_no_mail,man,man_with_gua_pi_mao,man_with_turban,mans_shoe,maple_leaf,mask,massage,meat_on_bone,mega,melon,memo,mens,metal,metro,microphone,microscope,milky_way,minibus,minidisc,mobile_phone_off,money_with_wings,moneybag,monkey,monkey_face,monorail,mortar_board,mount_fuji,mountain_bicyclist,mountain_cableway,mountain_railway,mouse,mouse2,movie_camera,moyai,muscle,mushroom,musical_keyboard,musical_note,musical_score,mute,nail_care,name_badge,neckbeard,necktie,negative_squared_cross_mark,neutral_face,new,new_moon,new_moon_with_face,newspaper,ng,nine,no_bell,no_bicycles,no_entry,no_entry_sign,no_good,no_mobile_phones,no_mouth,no_pedestrians,no_smoking,non-potable_water,nose,notebook,notebook_with_decorative_cover,notes,nut_and_bolt,o,o2,ocean,octocat,octopus,oden,office,ok,ok_hand,ok_woman,older_man,older_woman,on,oncoming_automobile,oncoming_bus,oncoming_police_car,oncoming_taxi,one,open_file_folder,open_hands,open_mouth,ophiuchus,orange_book,outbox_tray,ox,package,page_facing_up,page_with_curl,pager,palm_tree,panda_face,paperclip,parking,part_alternation_mark,partly_sunny,passport_control,paw_prints,peach,pear,pencil,pencil2,penguin,pensive,performing_arts,persevere,person_frowning,person_with_blond_hair,person_with_pouting_face,phone,pig,pig2,pig_nose,pill,pineapple,pisces,pizza,plus1,point_down,point_left,point_right,point_up,point_up_2,police_car,poodle,poop,post_office,postal_horn,postbox,potable_water,pouch,poultry_leg,pound,pouting_cat,pray,princess,punch,purple_heart,purse,pushpin,put_litter_in_its_place,question,rabbit,rabbit2,racehorse,radio,radio_button,rage,rage1,rage2,rage3,rage4,railway_car,rainbow,raised_hand,raised_hands,raising_hand,ram,ramen,rat,recycle,red_car,red_circle,registered,relaxed,relieved,repeat,repeat_one,restroom,revolving_hearts,rewind,ribbon,rice,rice_ball,rice_cracker,rice_scene,ring,rocket,roller_coaster,rooster,rose,rotating_light,round_pushpin,rowboat,ru,rugby_football,runner,running,running_shirt_with_sash,sa,sagittarius,sailboat,sake,sandal,santa,satellite,satisfied,saxophone,school,school_satchel,scissors,scorpius,scream,scream_cat,scroll,seat,secret,see_no_evil,seedling,seven,shaved_ice,sheep,shell,ship,shipit,shirt,shit,shoe,shower,signal_strength,six,six_pointed_star,ski,skull,sleeping,sleepy,slot_machine,small_blue_diamond,small_orange_diamond,small_red_triangle,small_red_triangle_down,smile,smile_cat,smiley,smiley_cat,smiling_imp,smirk,smirk_cat,smoking,snail,snake,snowboarder,snowflake,snowman,sob,soccer,soon,sos,sound,space_invader,spades,spaghetti,sparkle,sparkler,sparkles,sparkling_heart,speak_no_evil,speaker,speech_balloon,speedboat,squirrel,star,star2,stars,station,statue_of_liberty,steam_locomotive,stew,straight_ruler,strawberry,stuck_out_tongue,stuck_out_tongue_closed_eyes,stuck_out_tongue_winking_eye,sun_with_face,sunflower,sunglasses,sunny,sunrise,sunrise_over_mountains,surfer,sushi,suspect,suspension_railway,sweat,sweat_drops,sweat_smile,sweet_potato,swimmer,symbols,syringe,tada,tanabata_tree,tangerine,taurus,taxi,tea,telephone,telephone_receiver,telescope,tennis,tent,thought_balloon,three,thumbsdown,thumbsup,ticket,tiger,tiger2,tired_face,tm,toilet,tokyo_tower,tomato,tongue,top,tophat,tractor,traffic_light,train,train2,tram,triangular_flag_on_post,triangular_ruler,trident,triumph,trolleybus,trollface,trophy,tropical_drink,tropical_fish,truck,trumpet,tshirt,tulip,turtle,tv,twisted_rightwards_arrows,two,two_hearts,two_men_holding_hands,two_women_holding_hands,u5272,u5408,u55b6,u6307,u6708,u6709,u6e80,u7121,u7533,u7981,u7a7a,uk,umbrella,unamused,underage,unlock,up,us,v,vertical_traffic_light,vhs,vibration_mode,video_camera,video_game,violin,virgo,volcano,vs,walking,waning_crescent_moon,waning_gibbous_moon,warning,watch,water_buffalo,watermelon,wave,wavy_dash,waxing_crescent_moon,waxing_gibbous_moon,wc,weary,wedding,whale,whale2,wheelchair,white_check_mark,white_circle,white_flower,white_large_square,white_medium_small_square,white_medium_square,white_small_square,white_square_button,wind_chime,wine_glass,wink,wolf,woman,womans_clothes,womans_hat,womens,worried,wrench,x,yellow_heart,yen,yum,zap,zero,zzz",g=u.split(/,/),m=g.reduce(function(e,a){return e[a]=!0,e},{}),d={blacklist:{ids:[],classes:["no-emojify"],elements:["script","textarea","a","pre","code"]},tag_type:null,only_crawl_id:null,img_dir:"images/emoji",ignore_emoticons:!1,mode:"img"},h={img:"img",sprite:"span","data-uri":"span"};return n.prototype={validate:function(e,a,r){function i(){return n.lastEmojiTerminatedAt=_+a,s}var n=this,s=t(e);if(s){var l=e[0],_=l.length;if(0===a)return i();if(r.length===l.length+a)return i();var c=this.lastEmojiTerminatedAt===a;if(c)return i();if(o(r.charAt(a-1)))return i();var u=o(r.charAt(l.length+a));return u&&c?i():void 0}}},{defaultConfig:d,emojiNames:g,setConfig:function(e){Object.keys(d).forEach(function(a){a in e&&(d[a]=e[a])})},replace:s,run:l}}();return e}); \ No newline at end of file
diff --git a/web/templates/channel.html b/web/templates/channel.html
index 92aaaf02f..2af94e415 100644
--- a/web/templates/channel.html
+++ b/web/templates/channel.html
@@ -29,6 +29,7 @@
<div id="edit_mention_tab"></div>
<div id="get_link_modal"></div>
<div id="user_settings_modal"></div>
+ <div id="import_theme_modal"></div>
<div id="team_settings_modal"></div>
<div id="invite_member_modal"></div>
<div id="edit_channel_modal"></div>
diff --git a/web/templates/head.html b/web/templates/head.html
index af5c86bba..2b83119d8 100644
--- a/web/templates/head.html
+++ b/web/templates/head.html
@@ -25,10 +25,12 @@
<link rel="stylesheet" href="/static/css/bootstrap-3.3.5.min.css">
<link rel="stylesheet" href="/static/css/jasny-bootstrap.min.css" rel="stylesheet">
+ <link rel="stylesheet" href="/static/css/bootstrap-colorpicker.min.css" rel="stylesheet">
<script src="/static/js/react-with-addons-0.13.3.js"></script>
<script src="/static/js/jquery-1.11.1.js"></script>
<script src="/static/js/bootstrap-3.3.5.js"></script>
+ <script src="/static/js/bootstrap-colorpicker.min.js"></script>
<script src="/static/js/react-bootstrap-0.25.1.js"></script>
<link id="favicon" rel="icon" href="/static/images/favicon.ico" type="image/x-icon">
@@ -40,11 +42,6 @@
<script src="/static/js/jquery-dragster/jquery.dragster.js"></script>
- <script src="/static/js/emojify.min.js"></script>
- <script>
- emojify.setConfig({img_dir: '/static/images/emoji'});
- </script>
-
<style id="antiClickjack">body{display:none !important;}</style>
<script src="/static/js/bundle.js"></script>
<script type="text/javascript">
@@ -56,7 +53,7 @@
<script type="text/javascript">
if (window.config.SegmentDeveloperKey != null && window.config.SegmentDeveloperKey !== "") {
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.0.1";
- analytics.load(window.config.SegmentWriteKey);
+ analytics.load(window.config.SegmentDeveloperKey);
var user = window.UserStore.getCurrentUser(true);
if (user) {
analytics.identify(user.id, {
@@ -65,7 +62,6 @@
createdAt: user.create_at,
username: user.username,
team_id: user.team_id,
- team_domain: window.getSubDomain(),
id: user.id
});
}
@@ -77,28 +73,5 @@
analytics.track = function(){};
}
</script>
- <!-- Snowplow starts plowing -->
- <script type="text/javascript">
- if ('{{ .Props.AnalyticsUrl }}'.trim() !== '') {
- ;(function(p,l,o,w,i,n,g){if(!p[i]){p.GlobalSnowplowNamespace=p.GlobalSnowplowNamespace||[];
- p.GlobalSnowplowNamespace.push(i);p[i]=function(){(p[i].q=p[i].q||[]).push(arguments)
- };p[i].q=p[i].q||[];n=l.createElement(o);g=l.getElementsByTagName(o)[0];n.async=1;
- n.src=w;g.parentNode.insertBefore(n,g)}}(window,document,"script","//d1fc8wv8zag5ca.cloudfront.net/2.4.2/sp.js","snowplow"));
-
- window.snowplow('newTracker', 'cf', '{{ .Props.AnalyticsUrl }}', {
- appId: window.config.SiteName
- });
-
- var user = window.UserStore.getCurrentUser(true);
- if (user) {
- window.snowplow('setUserId', user.id);
- }
-
- window.snowplow('trackPageView');
- } else {
- window.snowplow = function(){};
- }
- </script>
- <!-- Snowplow stops plowing -->
</head>
{{end}}
diff --git a/web/web.go b/web/web.go
index 305e4f199..da7eff13d 100644
--- a/web/web.go
+++ b/web/web.go
@@ -9,11 +9,13 @@ import (
"github.com/gorilla/mux"
"github.com/mattermost/platform/api"
"github.com/mattermost/platform/model"
+ "github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
"github.com/mssola/user_agent"
"gopkg.in/fsnotify.v1"
"html/template"
"net/http"
+ "regexp"
"strconv"
"strings"
)
@@ -25,7 +27,7 @@ type HtmlTemplatePage api.Page
func NewHtmlTemplatePage(templateName string, title string) *HtmlTemplatePage {
if len(title) > 0 {
- title = utils.Cfg.ServiceSettings.SiteName + " - " + title
+ title = utils.Cfg.TeamSettings.SiteName + " - " + title
}
props := make(map[string]string)
@@ -63,6 +65,8 @@ func InitWeb() {
mainrouter.Handle("/admin_console", api.UserRequired(adminConsole)).Methods("GET")
+ mainrouter.Handle("/hooks/{id:[A-Za-z0-9]+}", api.ApiAppHandler(incomingWebhook)).Methods("POST")
+
// ----------------------------------------------------------------------------------------------
// *ANYTHING* team specific should go below this line
// ----------------------------------------------------------------------------------------------
@@ -143,7 +147,6 @@ func root(c *api.Context, w http.ResponseWriter, r *http.Request) {
if len(c.Session.UserId) == 0 {
page := NewHtmlTemplatePage("signup_team", "Signup")
- page.Props["AuthServices"] = model.ArrayToJson(utils.GetAllowedAuthServices())
page.Render(c, w)
} else {
page := NewHtmlTemplatePage("home", "Home")
@@ -159,7 +162,6 @@ func signup(c *api.Context, w http.ResponseWriter, r *http.Request) {
}
page := NewHtmlTemplatePage("signup_team", "Signup")
- page.Props["AuthServices"] = model.ArrayToJson(utils.GetAllowedAuthServices())
page.Render(c, w)
}
@@ -173,8 +175,7 @@ func login(c *api.Context, w http.ResponseWriter, r *http.Request) {
var team *model.Team
if tResult := <-api.Srv.Store.Team().GetByName(teamName); tResult.Err != nil {
l4g.Error("Couldn't find team name=%v, teamURL=%v, err=%v", teamName, c.GetTeamURL(), tResult.Err.Message)
- // This should probably do somthing nicer
- http.Redirect(w, r, "http://"+r.Host, http.StatusTemporaryRedirect)
+ http.Redirect(w, r, api.GetProtocol(r)+"://"+r.Host, http.StatusTemporaryRedirect)
return
} else {
team = tResult.Data.(*model.Team)
@@ -191,7 +192,6 @@ func login(c *api.Context, w http.ResponseWriter, r *http.Request) {
page := NewHtmlTemplatePage("login", "Login")
page.Props["TeamDisplayName"] = team.DisplayName
page.Props["TeamName"] = teamName
- page.Props["AuthServices"] = model.ArrayToJson(utils.GetAllowedAuthServices())
page.Render(c, w)
}
@@ -207,7 +207,7 @@ func signupTeamComplete(c *api.Context, w http.ResponseWriter, r *http.Request)
data := r.FormValue("d")
hash := r.FormValue("h")
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) {
c.Err = model.NewAppError("signupTeamComplete", "The signup link does not appear to be valid", "")
return
}
@@ -256,7 +256,7 @@ func signupUserComplete(c *api.Context, w http.ResponseWriter, r *http.Request)
}
} else {
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) {
c.Err = model.NewAppError("signupTeamComplete", "The signup link does not appear to be valid", "")
return
}
@@ -277,7 +277,6 @@ func signupUserComplete(c *api.Context, w http.ResponseWriter, r *http.Request)
page.Props["TeamId"] = props["id"]
page.Props["Data"] = data
page.Props["Hash"] = hash
- page.Props["AuthServices"] = model.ArrayToJson(utils.GetAllowedAuthServices())
page.Render(c, w)
}
@@ -355,6 +354,7 @@ func getChannel(c *api.Context, w http.ResponseWriter, r *http.Request) {
func verifyEmail(c *api.Context, w http.ResponseWriter, r *http.Request) {
resend := r.URL.Query().Get("resend")
+ resendSuccess := r.URL.Query().Get("resend_success")
name := r.URL.Query().Get("teamname")
email := r.URL.Query().Get("email")
hashedId := r.URL.Query().Get("hid")
@@ -375,7 +375,9 @@ func verifyEmail(c *api.Context, w http.ResponseWriter, r *http.Request) {
} else {
user := result.Data.(*model.User)
api.FireAndForgetVerifyEmail(user.Id, user.Email, team.Name, team.DisplayName, c.GetSiteURL(), c.GetTeamURLFromTeam(team))
- http.Redirect(w, r, "/", http.StatusFound)
+
+ newAddress := strings.Replace(r.URL.String(), "&resend=true", "&resend_success=true", -1)
+ http.Redirect(w, r, newAddress, http.StatusFound)
return
}
}
@@ -400,6 +402,7 @@ func verifyEmail(c *api.Context, w http.ResponseWriter, r *http.Request) {
page.Props["IsVerified"] = isVerified
page.Props["TeamURL"] = c.GetTeamURLFromTeam(team)
page.Props["UserEmail"] = email
+ page.Props["ResendSuccess"] = resendSuccess
page.Render(c, w)
}
@@ -418,7 +421,7 @@ func resetPassword(c *api.Context, w http.ResponseWriter, r *http.Request) {
if len(hash) == 0 || len(data) == 0 {
isResetLink = false
} else {
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.ResetSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.PasswordResetSalt)) {
c.Err = model.NewAppError("resetPassword", "The reset link does not appear to be valid", "")
return
}
@@ -480,7 +483,7 @@ func signupWithOAuth(c *api.Context, w http.ResponseWriter, r *http.Request) {
data := r.URL.Query().Get("d")
props := model.MapFromJson(strings.NewReader(data))
- if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.ServiceSettings.InviteSalt)) {
+ if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) {
c.Err = model.NewAppError("signupWithOAuth", "The signup link does not appear to be valid", "")
return
}
@@ -838,3 +841,84 @@ func getAccessToken(c *api.Context, w http.ResponseWriter, r *http.Request) {
w.Write([]byte(accessRsp.ToJson()))
}
+
+func incomingWebhook(c *api.Context, w http.ResponseWriter, r *http.Request) {
+ params := mux.Vars(r)
+ id := params["id"]
+
+ hchan := api.Srv.Store.Webhook().GetIncoming(id)
+
+ r.ParseForm()
+
+ props := model.MapFromJson(strings.NewReader(r.FormValue("payload")))
+
+ text := props["text"]
+ if len(text) == 0 {
+ c.Err = model.NewAppError("incomingWebhook", "No text specified", "")
+ return
+ }
+
+ channelName := props["channel"]
+
+ var hook *model.IncomingWebhook
+ if result := <-hchan; result.Err != nil {
+ c.Err = model.NewAppError("incomingWebhook", "Invalid webhook", "err="+result.Err.Message)
+ return
+ } else {
+ hook = result.Data.(*model.IncomingWebhook)
+ }
+
+ var channel *model.Channel
+ var cchan store.StoreChannel
+
+ if len(channelName) != 0 {
+ if channelName[0] == '@' {
+ if result := <-api.Srv.Store.User().GetByUsername(hook.TeamId, channelName[1:]); result.Err != nil {
+ c.Err = model.NewAppError("incomingWebhook", "Couldn't find the user", "err="+result.Err.Message)
+ return
+ } else {
+ channelName = model.GetDMNameFromIds(result.Data.(*model.User).Id, hook.UserId)
+ }
+ } else if channelName[0] == '#' {
+ channelName = channelName[1:]
+ }
+
+ cchan = api.Srv.Store.Channel().GetByName(hook.TeamId, channelName)
+ } else {
+ cchan = api.Srv.Store.Channel().Get(hook.ChannelId)
+ }
+
+ // parse links into Markdown format
+ linkWithTextRegex := regexp.MustCompile(`<([^<\|]+)\|([^>]+)>`)
+ text = linkWithTextRegex.ReplaceAllString(text, "[${2}](${1})")
+
+ linkRegex := regexp.MustCompile(`<\s*(\S*)\s*>`)
+ text = linkRegex.ReplaceAllString(text, "${1}")
+
+ if result := <-cchan; result.Err != nil {
+ c.Err = model.NewAppError("incomingWebhook", "Couldn't find the channel", "err="+result.Err.Message)
+ return
+ } else {
+ channel = result.Data.(*model.Channel)
+ }
+
+ pchan := api.Srv.Store.Channel().CheckPermissionsTo(hook.TeamId, channel.Id, hook.UserId)
+
+ post := &model.Post{UserId: hook.UserId, ChannelId: channel.Id, Message: text}
+
+ if !c.HasPermissionsToChannel(pchan, "createIncomingHook") && channel.Type != model.CHANNEL_OPEN {
+ c.Err = model.NewAppError("incomingWebhook", "Inappropriate channel permissions", "")
+ return
+ }
+
+ // create a mock session
+ c.Session = model.Session{UserId: hook.UserId, TeamId: hook.TeamId, IsOAuth: false}
+
+ if _, err := api.CreatePost(c, post, false); err != nil {
+ c.Err = model.NewAppError("incomingWebhook", "Error creating post", "err="+err.Message)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/plain")
+ w.Write([]byte("ok"))
+}
diff --git a/web/web_test.go b/web/web_test.go
index 3da7eb2dc..165c2ba09 100644
--- a/web/web_test.go
+++ b/web/web_test.go
@@ -25,7 +25,7 @@ func Setup() {
api.StartServer()
api.InitApi()
InitWeb()
- URL = "http://localhost:" + utils.Cfg.ServiceSettings.Port
+ URL = "http://localhost" + utils.Cfg.ServiceSettings.ListenAddress
ApiClient = model.NewClient(URL)
}
}
@@ -180,6 +180,51 @@ func TestGetAccessToken(t *testing.T) {
}
}
+func TestIncomingWebhook(t *testing.T) {
+ Setup()
+
+ team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
+ team = ApiClient.Must(ApiClient.CreateTeam(team)).Data.(*model.Team)
+
+ user := &model.User{TeamId: team.Id, Email: model.NewId() + "corey@test.com", Nickname: "Corey Hulen", Password: "pwd"}
+ user = ApiClient.Must(ApiClient.CreateUser(user, "")).Data.(*model.User)
+ store.Must(api.Srv.Store.User().VerifyEmail(user.Id))
+
+ ApiClient.LoginByEmail(team.Name, user.Email, "pwd")
+
+ channel1 := &model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
+ channel1 = ApiClient.Must(ApiClient.CreateChannel(channel1)).Data.(*model.Channel)
+
+ if utils.Cfg.ServiceSettings.EnableIncomingWebhooks {
+ hook1 := &model.IncomingWebhook{ChannelId: channel1.Id}
+ hook1 = ApiClient.Must(ApiClient.CreateIncomingWebhook(hook1)).Data.(*model.IncomingWebhook)
+
+ payload := "payload={\"text\": \"test text\"}"
+ if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err != nil {
+ t.Fatal(err)
+ }
+
+ payload = "payload={\"text\": \"\"}"
+ if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err == nil {
+ t.Fatal("should have errored - no text to post")
+ }
+
+ payload = "payload={\"text\": \"test text\", \"channel\": \"junk\"}"
+ if _, err := ApiClient.PostToWebhook(hook1.Id, payload); err == nil {
+ t.Fatal("should have errored - bad channel")
+ }
+
+ payload = "payload={\"text\": \"test text\"}"
+ if _, err := ApiClient.PostToWebhook("abc123", payload); err == nil {
+ t.Fatal("should have errored - bad hook")
+ }
+ } else {
+ if _, err := ApiClient.PostToWebhook("123", "123"); err == nil {
+ t.Fatal("should have failed - webhooks turned off")
+ }
+ }
+}
+
func TestZZWebTearDown(t *testing.T) {
// *IMPORTANT*
// This should be the last function in any test file