Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Copy of private Mr-ray repository to public github

  • Loading branch information...
commit 94e069eb20300896f9acf9dc578ed9b3512d5633 0 parents
Thomas Beverley authored
Showing with 13,586 additions and 0 deletions.
  1. BIN  .DS_Store
  2. +57 −0 LICENSE.rtf
  3. +14 −0 README
  4. +330 −0 actionWave.py
  5. +51 −0 app.yaml
  6. +57 −0 config.py
  7. BIN  dbtools/.DS_Store
  8. +19 −0 dbtools/__init__.py
  9. +21 −0 dbtools/dbConfig.py
  10. +44 −0 dbtools/dbmigration.py
  11. +25 −0 dbtools/memcacheConfig.py
  12. +102 −0 dbtools/models.py
  13. +102 −0 dbtools/sessionTools.py
  14. +221 −0 dbtools/settingsTools.py
  15. +161 −0 dbtools/waveTools.py
  16. +246 −0 emailInterface.py
  17. +19 −0 errors/__init__.py
  18. +26 −0 errors/friendlyCodes.py
  19. +84 −0 errors/interceptor.py
  20. +245 −0 errors/output.py
  21. +24 −0 errors/rayExceptions.py
  22. +389 −0 gadgetHandler.py
  23. +12 −0 index.yaml
  24. +19 −0 permission/__init__.py
  25. +22 −0 permission/rawTypes.py
  26. +76 −0 permission/readWrite.py
  27. +41 −0 redirects.py
  28. +98 −0 renderWave.py
  29. +187 −0 robot.py
  30. BIN  security/.DS_Store
  31. +18 −0 security/__init__.py
  32. +170 −0 security/decorators.py
  33. +137 −0 security/sessionCreation.py
  34. +2 −0  static/robots.txt
  35. BIN  templates/.DS_Store
  36. +22 −0 templates/cantcontactwave.html
  37. +4 −0 templates/components/errorcodereport.html
  38. +7 −0 templates/components/footer.html
  39. +23 −0 templates/components/header.html
  40. +8 −0 templates/components/javascriptconfig.html
  41. +22 −0 templates/denied.html
  42. +21 −0 templates/inadequatepermission.html
  43. +50 −0 templates/renderwave.html
  44. +22 −0 templates/robotremoved.html
  45. +21 −0 templates/standarderror.html
  46. +21 −0 templates/userdeleted.html
  47. +122 −0 utils.py
  48. +17 −0 waveapi/__init__.py
  49. +201 −0 waveapi/appengine_robot_runner.py
  50. +890 −0 waveapi/blip.py
  51. +374 −0 waveapi/blip_test.py
  52. +69 −0 waveapi/commandline_robot_runner.py
  53. +76 −0 waveapi/commandline_robot_runner_test.py
  54. +196 −0 waveapi/conf.py
  55. +329 −0 waveapi/element.py
  56. +171 −0 waveapi/element_test.py
  57. +25 −0 waveapi/errors.py
  58. +293 −0 waveapi/events.py
  59. +40 −0 waveapi/module_test_runner.py
  60. +22 −0 waveapi/oauth/LICENSE
  61. +523 −0 waveapi/oauth/__init__.py
  62. +418 −0 waveapi/ops.py
  63. +53 −0 waveapi/ops_test.py
  64. +500 −0 waveapi/robot.py
  65. +261 −0 waveapi/robot_test.py
  66. +44 −0 waveapi/run_unit_tests.py
  67. +19 −0 waveapi/simplejson/LICENSE
  68. +406 −0 waveapi/simplejson/__init__.py
  69. +411 −0 waveapi/simplejson/decoder.py
  70. +456 −0 waveapi/simplejson/encoder.py
  71. +40 −0 waveapi/simplejson/jsonfilter.py
  72. +119 −0 waveapi/simplejson/ordered_dict.py
  73. +67 −0 waveapi/simplejson/scanner.py
  74. +37 −0 waveapi/simplejson/tool.py
  75. +159 −0 waveapi/util.py
  76. +145 −0 waveapi/util_test.py
  77. +414 −0 waveapi/wavelet.py
  78. +176 −0 waveapi/wavelet_test.py
  79. +2 −0  waveapi/waveto_modifications
  80. +17 −0 waveto/__init__.py
  81. +97 −0 waveto/waveRpc.py
  82. +28 −0 waveto/waveletTools.py
  83. BIN  web/.DS_Store
  84. BIN  web/gadget/.DS_Store
  85. +41 −0 web/gadget/addparticipants.xml
  86. +36 −0 web/gadget/addparticipantsv2.xml
  87. BIN  web/gadget/js/.DS_Store
  88. +240 −0 web/gadget/js/addparticipants.js
  89. +556 −0 web/gadget/js/addparticipantsv2.js
  90. +122 −0 web/gadget/style/addparticipants.css
  91. +147 −0 web/gadget/style/addparticipantsv2.css
  92. +1,155 −0 web/js/renderwavev2.js
  93. +64 −0 web/js/renderwavev2.min.js
  94. BIN  web/lib/.DS_Store
  95. +142 −0 web/lib/base64.js
  96. +380 −0 web/lib/json2.js
  97. BIN  web/media/.DS_Store
  98. BIN  web/media/favicon.ico
  99. BIN  web/media/gadgetholder.png
  100. BIN  web/media/icon.png
  101. BIN  web/media/icon_base.png
  102. BIN  web/media/icon_proxyfor.png
  103. BIN  web/media/icon_public.png
  104. BIN  web/media/icon_waver.png
  105. BIN  web/media/inline.png
  106. BIN  web/media/inputbackground.png
  107. BIN  web/media/reply_icon.png
  108. BIN  web/media/working.gif
  109. BIN  web/media/workingbar.gif
  110. BIN  web/media/workinground.gif
  111. +8 −0 web/mr-ray-installer.xml
  112. BIN  web/style/.DS_Store
  113. +22 −0 web/style/errorpage.css
  114. +25 −0 web/style/header.css
  115. +191 −0 web/style/renderwave.css
BIN  .DS_Store
Binary file not shown
57 LICENSE.rtf
@@ -0,0 +1,57 @@
+{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350
+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+{\colortbl;\red255\green255\blue255;\red38\green38\blue38;\red44\green62\blue125;}
+{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid1}}
+{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}}
+\paperw11900\paperh16840\margl1440\margr1440\vieww21600\viewh16680\viewkind0
+\deftab720
+\pard\pardeftab720\sl440\sa300\ql\qnatural
+
+\f0\fs30 \cf2 Apache License\uc0\u8232 \u8232 Version 2.0, January 2004\u8232 \u8232 {\field{\*\fldinst{HYPERLINK "http://www.apache.org/licenses/"}}{\fldrslt
+\b \cf3 http://www.apache.org/licenses/}}\
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\
+\pard\pardeftab720\sl440\sa300\ql\qnatural
+
+\b \cf3 1. Definitions
+\b0 \cf2 .\
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.\
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."\
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\
+
+\b \cf3 2. Grant of Copyright License
+\b0 \cf2 . Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\
+
+\b \cf3 3. Grant of Patent License
+\b0 \cf2 . Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\
+
+\b \cf3 4. Redistribution
+\b0 \cf2 . You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\
+\pard\tx220\tx720\pardeftab720\li720\fi-720\sl440\sa300\ql\qnatural
+\ls1\ilvl0\cf2 {\listtext 1. }You must give any other recipients of the Work or Derivative Works a copy of this License; and\
+{\listtext 2. }You must cause any modified files to carry prominent notices stating that You changed the files; and\
+{\listtext 3. }You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\
+{\listtext 4. }If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\
+\pard\pardeftab720\sl440\sa300\ql\qnatural
+
+\b \cf3 5. Submission of Contributions
+\b0 \cf2 . Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\
+
+\b \cf3 6. Trademarks
+\b0 \cf2 . This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\
+
+\b \cf3 7. Disclaimer of Warranty
+\b0 \cf2 . Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\
+
+\b \cf3 8. Limitation of Liability
+\b0 \cf2 . In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\
+
+\b \cf3 9. Accepting Warranty or Additional Liability
+\b0 \cf2 . While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\
+END OF TERMS AND CONDITIONS}
14 README
@@ -0,0 +1,14 @@
+{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350
+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+{\colortbl;\red255\green255\blue255;}
+\paperw11900\paperh16840\margl1440\margr1440\vieww9000\viewh8400\viewkind0
+\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural
+
+\f0\fs24 \cf0 *Setting up Mr-Ray on your own server**\
+\
+Mr-Ray should work pretty much out the box you just need to do a little configuration.\
+\
+In config.py you will need to change the following variables:\
+*ROBOT_IDENT* This should be the appspot identifier for your application\
+*CONSUMER_KEY* This should be your oauth consumer key for wave\
+*CONSUMER_SECRET* This should be your oauth consumer secret for wave}
330 actionWave.py
@@ -0,0 +1,330 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Handles requests incoming at wave/action and acts upon them
+'''
+import cgi
+import logging
+import re
+import urllib
+
+import config
+import emailInterface
+from errors.rayExceptions import MalformedRequest
+from errors.interceptor import *
+from permission import rawTypes as pt_raw
+from security import sessionCreation
+from security.decorators import *
+import utils
+
+from dbtools import settingsTools
+from dbtools import sessionTools
+from waveto import waveRpc
+
+from waveapi import robot
+from waveapi import simplejson
+
+from google.appengine.ext import deferred
+from google.appengine.ext import webapp
+from google.appengine.ext.webapp.util import run_wsgi_app
+
+mrray = None
+
+class ActionWave(webapp.RequestHandler):
+
+ ##########################################################################
+ # POST / GET request handlers
+ ##########################################################################
+ @isAuthenticated(False)
+ @interceptExceptions(False)
+ def post(self):
+ '''
+ Handles the incoming post request and performs the relevant action on
+ the wave.
+ '''
+ logging.info("POST: /wave/action/")
+ #Fetch the auth values from the url + form values
+ incoming_json = cgi.escape(self.request.body)
+ self.incoming = simplejson.loads(incoming_json)
+
+ self.wave_id = urllib.unquote(self.incoming.get("waveid", ""))
+ self.wavelet_id = urllib.unquote(self.incoming.get("waveletid", ""))
+ self.email = urllib.unquote(self.incoming.get("email", ""))
+ self.auth_token = self.incoming.get("auth", "")
+ self.action = self.incoming.get("action", None)
+
+ logging.info("Request waveid: " + self.wave_id + " waveletid: " + self.wavelet_id + " email: " + self.email + " auth token: " + self.auth_token)
+
+ if self.action == "REPLY":
+ return self._replyRequest()
+ elif self.action == "READ":
+ return self._readRequest()
+ elif self.action == "REFRESH":
+ return self._refreshRequest()
+ else:
+ return self._malformedRequest()
+
+ ##########################################################################
+ # Request handlers for different request types
+ ##########################################################################
+ @hasPermission(False, pt_raw.RW['READ_WRITE'])
+ def _replyRequest(self):
+ '''
+ Launches a reply request with ensuring permissions are checked etc
+ '''
+ logging.info("This is a REPLY request")
+ settingsTools.markSeenChanges(key={ 'wave_id' : self.wave_id,
+ 'wavelet_id': self.wavelet_id,
+ 'email' : self.email})
+ self._UserReplies()
+
+ @hasPermission(False, pt_raw.RW['READ_WRITE'])
+ def _readRequest(self):
+ '''
+ Launches a read request ensuring permissions are checked etc
+ Note: this endpoint is accessible via public but is never shown on the wave
+ '''
+ logging.info("This is a READ request")
+ settingsTools.markSeenChanges(key={ 'wave_id' : self.wave_id,
+ 'wavelet_id': self.wavelet_id,
+ 'email' : self.email})
+ self.__UserReads(self.incoming.get('blipid', ""))
+ self.response.set_status(201)
+
+ @hasPermission(False, pt_raw.RW['READ'])
+ def _refreshRequest(self):
+ '''
+ Launches a refresh request ensuring permissions are checked etc
+ '''
+ logging.info("This is a REFRESH request")
+ self._UserRefresh()
+
+ @hasPermission(False, pt_raw.RW['READ'])
+ def _malformedRequest(self):
+ '''
+ Launches a malformed request ensuring permissions are checked etc
+ '''
+ logging.warn("The requested service " + str(self.action) + " was requested but is not valid")
+ raise MalformedRequest("The requested service " + str(self.action) + " was requested but is not valid")
+
+
+ ##########################################################################
+ # Request support methods for carrying out actions
+ ##########################################################################
+ def _UserReplies(self):
+ '''
+ Sends a reply to wave from the user along with other tasks such as
+ marking the wave read etc.
+ '''
+ #Modify requirements if the wave is public
+ if sessionTools.isPublic(sessionTools.get( self.wave_id, self.wavelet_id, self.email)):
+ self._PublicReplies()
+ else:
+ #Fetch the wavelet and do some house-keeping
+ wavelet = waveRpc.retry_fetch_wavelet( config.HTTP_IMPORTANT_RETRY,
+ mrray,
+ self.wave_id,
+ self.wavelet_id)
+
+ try:
+ wavelet.robot_address = config.ROBOT_EMAIL
+ except:
+ pass#The wavelet already has the robot address
+ proxy_for = utils.getProxyForFromEmail(self.email)
+
+ if wavelet.participants.get_role(config.ROBOT_IDENT + "+" + proxy_for + "@" + config.ROBOT_DOMAIN) == wavelet.participants.ROLE_READ_ONLY:
+ #TODO wrong exception raised here
+ raise waveRpc.NotParticipantException("Wave permissions do not permit reply")
+ if wavelet.participants.get_role(config.ROBOT_EMAIL) == wavelet.participants.ROLE_READ_ONLY:
+ #TODO wrong exception raised here
+ raise waveRpc.NotParticipantException("Wave permissions do not permit reply")
+
+ wavelet.add_proxying_participant(proxy_for)
+ self.__InsertBlipIntoWavelet(wavelet, proxy_for)
+ self.__AlertEmailParticipants(wavelet, self.email+"(via Mr-Ray)")
+ waveRpc.retry_submit(config.HTTP_IMPORTANT_RETRY, mrray, wavelet)
+
+ #Re-fetch the new (updated) wavelet
+ new_wavelet_data = waveRpc.retry_fetch_wavelet_json(config.HTTP_IMPORTANT_RETRY,
+ mrray,
+ self.wave_id,
+ self.wavelet_id)
+ self.__MarkNewBlipRead(new_wavelet_data)
+
+ #Write the response
+ wavelet_json = utils.construct_wavelet_json_for_http_response( new_wavelet_data,
+ self.wave_id,
+ self.wavelet_id,
+ self.email)
+ self.response.headers['Content-Type'] = 'application/json'
+ self.response.out.write(wavelet_json)
+ self.response.set_status(201)
+
+ def _PublicReplies(self):
+ '''
+ Sends a reply to wave from the public user
+ Maybe consider merging this into _publicReplies in the future. Methods are very similar
+ '''
+ self.name = self.incoming.get("name", None)
+ if not self.name:
+ logger.warn("The response came from a public wave and expected the 'name' field but was not found")
+ raise MalformedRequest("The response came from a public wave and expected the 'name' field but was not found")
+ if not re.match("^[a-zA-Z0-9_]+$", self.name):
+ logger.warn("The response came from a public wave and expected the 'name' field to only contain [a-zA-Z0-9_] but it was " + name)
+ raise MalformedRequest("The response came from a public wave and expected the 'name' field to only contain [a-zA-Z0-9_] but it was " + name)
+
+ #Fetch the wavelet and do some house-keeping
+ wavelet = waveRpc.retry_fetch_wavelet( config.HTTP_IMPORTANT_RETRY,
+ mrray,
+ self.wave_id,
+ self.wavelet_id)
+
+ try:
+ wavelet.robot_address = config.ROBOT_EMAIL
+ except:
+ pass#The wavelet already has the robot address
+ proxy_for = utils.getProxyForFromPublic(self.name)
+
+ if wavelet.participants.get_role(config.ROBOT_IDENT + "+" + proxy_for + "@" + config.ROBOT_DOMAIN) == wavelet.participants.ROLE_READ_ONLY:
+ #TODO wrong exception raised here
+ raise waveRpc.NotParticipantException("Wave permissions do not permit reply")
+ if wavelet.participants.get_role(config.ROBOT_EMAIL) == wavelet.participants.ROLE_READ_ONLY:
+ #TODO wrong exception raised here
+ raise waveRpc.NotParticipantException("Wave permissions do not permit reply")
+
+ wavelet.add_proxying_participant(proxy_for)
+ self.__InsertBlipIntoWavelet(wavelet, proxy_for)
+ self.__AlertEmailParticipants(wavelet, self.name + "(via Mr-Ray Public)")
+ waveRpc.retry_submit(config.HTTP_IMPORTANT_RETRY, mrray, wavelet)
+
+ #Re-fetch the new (updated) wavelet
+ new_wavelet_data = waveRpc.retry_fetch_wavelet_json(config.HTTP_IMPORTANT_RETRY,
+ mrray,
+ self.wave_id,
+ self.wavelet_id)
+
+ #Write the response
+ wavelet_json = utils.construct_wavelet_json_for_http_response( new_wavelet_data,
+ self.wave_id,
+ self.wavelet_id,
+ self.email)
+ self.response.headers['Content-Type'] = 'application/json'
+ self.response.out.write(wavelet_json)
+ self.response.set_status(201)
+
+ def _UserRefresh(self):
+ '''
+ Fetches and returns the wavelet json for a user
+ '''
+ new_wavelet_data = waveRpc.retry_fetch_wavelet_json(config.HTTP_LOSSY_RETRY,
+ mrray,
+ self.wave_id,
+ self.wavelet_id)
+
+ wavelet_json = utils.construct_wavelet_json_for_http_response( new_wavelet_data,
+ self.wave_id,
+ self.wavelet_id,
+ self.email)
+ self.response.headers['Content-Type'] = 'application/json'
+ self.response.out.write(wavelet_json)
+
+
+
+ def __InsertBlipIntoWavelet(self, wavelet, proxy_for):
+ '''
+ Inserts a blip into the wavelet at the specified position with the
+ specified content
+ @param wavelet: the wavelet to add the blip to
+ @param proxy_for: the proxy_for user to send this request from
+ '''
+ #Insert blip into the wavelet
+ blip_id = self.incoming.get('blipid', "")
+ reply = self.incoming.get('reply', '')
+ blip = wavelet.blips.get(blip_id, None)
+ if(blip == None):
+ wavelet.proxy_for(proxy_for).reply().append(reply)
+ else:
+ blip.proxy_for(proxy_for).reply().append(reply)
+
+ def __AlertEmailParticipants(self, wavelet, who_changed):
+ '''
+ Send an email out to any other proxy-for participants in the wave
+ @param wavelet: the wavelet that the proxy-for participants are
+ subscribed to
+ @param who_changed: the friendly name of who changed the wave
+ '''
+ #Alert other e-mail participants that a new blip has been posted
+ sessions = sessionTools.fetch(wavelet.wave_id, wavelet.wavelet_id)
+
+ for userSession in sessions:
+ if not userSession.email == self.email and not sessionTools.isPublic(userSession):
+ userSettings = settingsTools.get(userSession)
+ if not userSettings.unseen_changes and not userSettings.rw_permission == pt_raw.RW['DELETED']:
+ deferred.defer(
+ emailInterface.sendNotificationEmail,
+ sessionCreation.regenerateUser( wavelet.wave_id,
+ wavelet.wavelet_id,
+ userSession.email ),
+ wavelet.wave_id,
+ wavelet.wavelet_id,
+ userSession.email,
+ self.email,
+ wavelet.title,
+ who_modified_display=who_changed)
+
+ settingsTools.markUnseenChanges(session=userSession)
+
+ def __MarkNewBlipRead(self, new_wavelet_data):
+ '''
+ Marks the new blip as read for the user so they know they have seen it
+ already
+ @param new_wavelet_data: the new wavelet from the server with the new
+ blip included
+ '''
+ #Mark new blip read
+ blip_id = self.incoming.get('blipid', "")
+ new_parent_blip = new_wavelet_data.get('wavelet').blips.get(blip_id, None)
+ if new_parent_blip:
+ child_blips = new_parent_blip.child_blips
+ for b in child_blips:
+ if config.ROBOT_IDENT + "+" + utils.getProxyForFromEmail(self.email) + "@" + config.ROBOT_DOMAIN in b.contributors:
+ self.__UserReads(b.blip_id)
+
+
+ def __UserReads(self, blip_id):
+ '''
+ Marks the given blip as read
+ @param blip_id: the id of the blip to mark as read
+ '''
+ if not blip_id:
+ return
+
+ #Update the database
+ settingsTools.userReadsBlip(blip_id, key={ 'wave_id' : self.wave_id,
+ 'wavelet_id': self.wavelet_id,
+ 'email' : self.email})
+
+
+if __name__=="__main__":
+ logging.info("Creating robot: /wave/action/")
+
+ mrray = robot.Robot(config.ROBOT_IDENT)
+ mrray.setup_oauth(config.CONSUMER_KEY, config.CONSUMER_SECRET, server_rpc_base=config.WAVE_SERVER_RPC)
+
+ run_wsgi_app( webapp.WSGIApplication(
+ [('/wave/action/', ActionWave)]
+ ))
51 app.yaml
@@ -0,0 +1,51 @@
+application: mr-ray
+version: 1
+runtime: python
+api_version: 1
+
+default_expiration: "5d"
+
+handlers:
+- url: /web
+ static_dir: web
+
+- url: /wave
+ script: renderWave.py
+
+- url: /wave/action/
+ script: actionWave.py
+
+- url: /favicon.ico
+ static_files: web/media/favicon.ico
+ upload: web/media/favicon.ico
+
+- url: /robots.txt
+ static_files: static/robots.txt
+ upload: static/robots.txt
+
+- url: /_ah/queue/deferred
+ script: $PYTHON_LIB/google/appengine/ext/deferred/deferred.py
+ login: admin
+
+
+
+
+
+- url: /
+ script: redirects.py
+
+
+- url: /_wave/capabilities.xml
+ script: robot.py
+
+- url: /_wave/robot/profile
+ script: robot.py
+
+- url: /_wave/robot/jsonrpc
+ script: robot.py
+
+- url: /_wave/verify_token
+ script: robot.py
+
+inbound_services:
+- mail
57 config.py
@@ -0,0 +1,57 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+A set of generic configuration variables used throughout the system
+'''
+#Robot web configuration/details
+ROBOT_IDENT= "mr-ray-open"
+ROBOT_PROFILE_URL = "https://github.com/waveto/mr-ray-open"
+ROBOT_DOMAIN = "appspot.com"
+ROBOT_EMAIL_DOMAIN = "appspotmail.com"
+ROBOT_EMAIL = ROBOT_IDENT + "@" + ROBOT_DOMAIN
+ROBOT_EMAIL_SEND_NOTIFICATION = "noreply-notification@" + ROBOT_IDENT + "." + ROBOT_EMAIL_DOMAIN
+ROBOT_EMAIL_SENDER_NAME = "Mr Ray open the Wav-e-mail bot"
+ROBOT_WEB = "http://" + ROBOT_IDENT + "." + ROBOT_DOMAIN + "/"
+
+#Oauth configuration
+
+#(Default config for mr-ray)
+if ROBOT_IDENT == "mr-ray-open":
+ CONSUMER_KEY = "YOUR CONSUMER KEY"
+ CONSUMER_SECRET = "YOUR CONSUMER SECRET"
+
+if ROBOT_IDENT == "mr-ray-open-test":
+ #(Default config for mr-ray-test)
+ CONSUMER_KEY = "YOUR CONSUMER SECRET"
+ CONSUMER_SECRET = "YOUR CONSUMER SECRET"
+
+WAVE_SERVER_RPC = "http://gmodules.com/api/rpc"
+
+#Gadgets
+ADD_PARTICIPANTS_GADGET_URL1 = ROBOT_WEB + "web/gadget/addparticipants.xml"
+ADD_PARTICIPANTS_GADGET_URL2 = ROBOT_WEB + "web/gadget/addparticipantsv2.xml"
+
+
+#Proxy for participants
+PROXY_FOR_AT_REPLACE = "-_at_-"
+
+#Contacting external wave service
+HTTP_LOSSY_RETRY = 2
+HTTP_IMPORTANT_RETRY = 4
+
+#Public users
+PUBLIC_EMAIL = "mrrayopen-public@wave.to"
BIN  dbtools/.DS_Store
Binary file not shown
19 dbtools/__init__.py
@@ -0,0 +1,19 @@
+#!/usr/bin/python
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+
+"""Declares the api package"""
21 dbtools/dbConfig.py
@@ -0,0 +1,21 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+A set of configuration variables used for database entries
+'''
+KEY_PREFIX = { "SETTINGS" : "",#This is blank as there is already data in the wild
+ "FOLLOWED_WAVE" : "flwdwv:/"}
44 dbtools/dbmigration.py
@@ -0,0 +1,44 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Methods used for migrating database models between versions
+'''
+from models import Settings
+import settingsTools
+import sessionTools
+
+from waveapi import simplejson
+
+def migratev1tov2(sessions):
+ '''
+ Looks at the provided session and if it is running version 1 migrates it
+ to version 2
+ @param session: the sessions to potentially migrate
+ '''
+ for session in sessions:
+ if session and session.version == 1:
+ settings = Settings(read_blips = simplejson.loads(session.read_blips or '[]'),
+ unseen_changes = session.unseenChanges,
+ parent = session,
+ key_name = settingsTools.generateKey(session.wave_id,
+ session.wavelet_id,
+ session.email))
+ settingsTools.put(settings, session.wave_id, session.wavelet_id, session.email)
+ session.version = 2
+ session.read_blips = None
+ session.unseenChanges = None
+ sessionTools.put(session)
25 dbtools/memcacheConfig.py
@@ -0,0 +1,25 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Set of configuration variables used for configuring memcache
+'''
+DEFAULT_EXPIRE_SECS = 300
+
+PREFIX = { "SESSION" : "sess:/",
+ "SETTINGS" : "sett:/",
+ "FOLLOWED_WAVE" : "flwdwv:/",
+ "WAVE_META" : "wvmeta:/"}
102 dbtools/models.py
@@ -0,0 +1,102 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Database models
+'''
+from google.appengine.api import datastore_types
+from google.appengine.ext import db
+
+from permission import rawTypes as pt_raw
+
+from waveapi import simplejson
+
+class JSONList(db.Property):
+ def get_value_for_datastore(self, model_instance):
+ value = super(JSONList, self).get_value_for_datastore(model_instance)
+ return self._deflate(value)
+ def validate(self, value):
+ return self._inflate(value)
+ def make_value_from_datastore(self, value):
+ return self._inflate(value)
+ def _inflate(self, value):
+ if value is None:
+ return []
+ if isinstance(value, unicode) or isinstance(value, str):
+ return simplejson.loads(str(value))
+ return value
+ def _deflate(self, value):
+ return db.Text(simplejson.dumps(value))
+ data_type = datastore_types.Text
+
+class JSONMap(db.Property):
+ def get_value_for_datastore(self, model_instance):
+ value = super(JSONMap, self).get_value_for_datastore(model_instance)
+ return self._deflate(value)
+ def validate(self, value):
+ return self._inflate(value)
+ def make_value_from_datastore(self, value):
+ return self._inflate(value)
+ def _inflate(self, value):
+ if value is None:
+ return {}
+ if isinstance(value, unicode) or isinstance(value, str):
+ return simplejson.loads(str(value))
+ return value
+ def _deflate(self, value):
+ return db.Text(simplejson.dumps(value))
+ data_type = datastore_types.Text
+
+class Session(db.Model):
+ """
+ Model that is used to record the users access token + session data etc
+ This is a root type and thus read/writes will not be transactionally safe
+ """
+ wave_id = db.StringProperty(required=True)
+ wavelet_id = db.StringProperty(required=True)
+ email = db.StringProperty(required=True)
+ auth_token = db.StringProperty(required=True)
+ version = db.IntegerProperty(default=1)
+
+ #Depricated fields. DO NOT USE!
+ read_blips = db.TextProperty(required=False)
+ unseenChanges = db.BooleanProperty(required=False, default=False)
+
+class Settings(db.Model):
+ """
+ Model that is used to record users session settings
+ Settings parent should always be set to a Session so read/writes can be
+ transactionally safe
+ """
+ read_blips = JSONList()
+ unseen_changes = db.BooleanProperty(default=False)#Default for migration. Users will get 1 rouge e-mail
+ rw_permission = db.StringProperty(required=True, default=pt_raw.RW['READ_WRITE'])#Default for migration when we only had email users with rw permission
+
+class FollowedWave(db.Model):
+ """
+ Model that is used to record a wave
+ This is a root type and thus read/writes will not be transactionally safe
+ """
+ wave_id = db.StringProperty(required=True)
+ wavelet_id = db.StringProperty(required=True)
+
+class WaveMeta(db.Model):
+ """
+ Model that can hold meta data about a wave
+ Parent should always be set to a FollowedWave so read/writes can be
+ transactionally safe
+ """
+ participant_profiles = JSONMap()
102 dbtools/sessionTools.py
@@ -0,0 +1,102 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Methods to make using Session models easier
+'''
+import base64
+
+import config
+import dbmigration
+import memcacheConfig
+from models import Session
+
+from waveapi import simplejson
+
+from google.appengine.api import memcache
+
+def fetch(wave_id, wavelet_id):
+ '''
+ Uses memcache or the datastore to get fetch sessions by wave_id and
+ wavelet_id
+ @param wave_id: the id of the session to fetch
+ @param wavelet_id: the if of the session to fetch
+
+ @return the sessions using the most efficient means possible or None if it
+ couldn't be found
+ '''
+ key = base64.b64encode( memcacheConfig.PREFIX['SESSION'] +
+ wave_id + wavelet_id)
+ sessions = memcache.get(key)
+ if not sessions == None:
+ dbmigration.migratev1tov2(sessions)
+ return sessions
+ else:
+ query = Session.all()
+ query.filter("wave_id =", wave_id)
+ query.filter("wavelet_id =", wavelet_id)
+ sessions = query.fetch(100)
+ dbmigration.migratev1tov2(sessions)
+ memcache.add(key, sessions, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
+ return sessions
+
+def get(wave_id, wavelet_id, email):
+ '''
+ Uses memcache or the datastore to fetch a single session by wave_id,
+ wavelet_id and email
+ @param wave_id: the id of the session to fetch
+ @param wavelet_id: the id of the session to fetch
+ @param email: the email of the session to fetch
+
+ @return the session using the most efficient means possible or None if it
+ couldn't be found
+ '''
+ key = base64.b64encode( memcacheConfig.PREFIX['SESSION'] +
+ wave_id + wavelet_id + email)
+ session = memcache.get(key)
+ if not session == None:
+ dbmigration.migratev1tov2([session])
+ return session
+ else:
+ query = Session.all()
+ query.filter("wave_id =", wave_id)
+ query.filter("wavelet_id =", wavelet_id)
+ query.filter("email =", email)
+ session = query.get()
+ dbmigration.migratev1tov2([session])
+ memcache.add(key, session, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
+ return session
+
+def put(session):
+ '''
+ Saves the session to the datastore and removes it from memcache
+ @param session: the session to save
+ '''
+ session.put()
+ memcache.delete(base64.b64encode( memcacheConfig.PREFIX['SESSION'] +
+ session.wave_id +
+ session.wavelet_id))
+ memcache.delete(base64.b64encode( memcacheConfig.PREFIX['SESSION'] +
+ session.wave_id +
+ session.wavelet_id +
+ session.email))
+
+def isPublic(session):
+ '''
+ @param session: a session object to test
+ @return True if the session is a public session.
+ '''
+ return session.email == config.PUBLIC_EMAIL
221 dbtools/settingsTools.py
@@ -0,0 +1,221 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Methods to make using Settings models easier
+'''
+import base64
+
+import dbConfig
+import memcacheConfig
+from models import Settings
+import sessionTools
+
+from google.appengine.api import memcache
+from google.appengine.ext import db
+
+def generateKey(wave_id, wavelet_id, email):
+ '''
+ Generates a key for a settings tuple
+ @param wave_id: the wave id of the parent
+ @param wavelet_id: the wavelet id of the parent
+ @param email: the email of the parent
+ @return the key that can be used for this tuple
+ '''
+ return dbConfig.KEY_PREFIX["SETTINGS"] + wave_id + "|" + wavelet_id + "|" + email
+
+def get(session):
+ '''
+ Uses memcache or the datastore to fetch a single setting by wave_id,
+ wavelet_id and email. Ideally this should fetch session only if needed but
+ this wouldn't work with the appengine transaction framework.
+ @transaction_safe
+ @param session: the parent session object
+
+ @return the setting using the most efficient means possible or None if it
+ couldn't be found
+ '''
+ if not session:
+ return None
+ key = base64.b64encode( memcacheConfig.PREFIX['SETTINGS'] +
+ session.wave_id +
+ session.wavelet_id +
+ session.email)
+ setting = memcache.get(key)
+ if not setting == None:
+ return setting
+ else:
+ query = Settings.all()
+ query.ancestor(session)
+ setting = query.get()
+ memcache.add(key, setting, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
+ return setting
+
+def put(setting, wave_id, wavelet_id, email):
+ '''
+ Saves the setting to the datastore and removes it from memcache
+ @transaction_safe
+ @param setting: the setting to save
+ @param wave_id: the wave id of the settings parent
+ @param wavelet_id: the wavelet id of the settings parent
+ @param email: the email of the settings parent
+ '''
+ setting.put()
+ memcache.delete(base64.b64encode( memcacheConfig.PREFIX['SETTINGS'] +
+ wave_id +
+ wavelet_id +
+ email))
+
+def markSeenChanges(key=None, session=None):
+ '''
+ Marks that a user has seen changes in a wave. Supply one of the optional
+ arguments. Supplying session is always more efficient if you already have
+ the value
+ @param key=None: a dict containing wave_id, wavelet_id and email
+ @param session=None: the parent session object
+ '''
+ if not key == None:
+ _updateUnseenChanges( key['wave_id'],
+ key['wavelet_id'],
+ key['email'],
+ False,
+ None)
+ elif not session == None:
+ _updateUnseenChanges( session.wave_id,
+ session.wavelet_id,
+ session.email,
+ False,
+ session)
+
+
+
+def markUnseenChanges(key=None, session=None):
+ '''
+ Marks that a user has seen new unseen changes in a wave. Supply one of the
+ optional arguments. Supplying session is always more efficient if you
+ already have the value
+ @param key=None: a dict containing wave_id, wavelet_id and email
+ @param session=None: the parent session object
+ '''
+ if not key == None:
+ _updateUnseenChanges( key['wave_id'],
+ key['wavelet_id'],
+ key['email'],
+ True,
+ None)
+ elif not session == None:
+ _updateUnseenChanges( session.wave_id,
+ session.wavelet_id,
+ session.email,
+ True,
+ session)
+
+
+def _updateUnseenChanges(wave_id, wavelet_id, email, value, session):
+ '''
+ Changes the value of unseen_changes in a nice transaction safe way
+ @param wave_id: the wave id of the session to modify
+ @param wavelet_id: the wavelet id of the session to modify
+ @param email: the email of the session to modify
+ @param value: the new value for unseen_changes
+ @param session: if provided uses given session, if None fetches from db
+ '''
+ if session == None:
+ session = sessionTools.get(wave_id, wavelet_id, email)
+
+ def worker(session, wave_id, wavelet_id, email, value):
+ '''
+ @transaction_safe
+ '''
+ settings = get(session)
+ if settings:
+ settings.unseen_changes = value
+ put(settings, wave_id, wavelet_id, email)
+
+ db.run_in_transaction(worker, session, wave_id, wavelet_id, email, value)
+
+def userReadsBlip(blip_id, key=None, session=None):
+ '''
+ Marks a single blip read for this user. Supply one of the optional
+ arguments. Supplying session is always more efficient if you
+ already have the value
+ @param key=None: a dict containing wave_id, wavelet_id and email
+ @param session=None: the parent session object
+ @param blip_id: the blip that is to be marked read
+ '''
+ if session == None:
+ session = sessionTools.get(key['wave_id'], key['wavelet_id'], key['email'])
+
+ def worker(session, blip_id):
+ '''
+ @transaction_safe
+ '''
+ settings = get(session)
+ if settings:
+ if not blip_id in settings.read_blips:
+ settings.read_blips.append(blip_id)
+ put(settings, session.wave_id, session.wavelet_id, session.email)
+
+ db.run_in_transaction(worker, session, blip_id)
+
+def blipChanges(blip_id, key=None, session=None):
+ '''
+ Marks a single blip unread for this user. Supply one of the optional
+ arguments. Supplying session is always more efficient if you
+ already have the value
+ @param key=None: a dict containing wave_id, wavelet_id and email
+ @param session=None: the parent session object
+ @param blip_id: the blip that is to be marked read
+ '''
+ if blip_id == None:
+ return
+ if session == None:
+ session = sessionTools.get(key['wave_id'], key['wavelet_id'], key['email'])
+
+ def worker(session, blip_id):
+ '''
+ @transaction_safe
+ '''
+ settings = get(session)
+ if settings:
+ if blip_id in settings.read_blips:
+ settings.read_blips.remove(blip_id)
+ put(settings, session.wave_id, session.wavelet_id, session.email)
+
+ db.run_in_transaction(worker, session, blip_id)
+
+def changeRWPermission(new_permission, key=None, session=None):
+ '''
+ Changes the RW permission for this session. Supply one of the optional
+ arguments. Supplying session is always more efficient if you already have
+ the value.
+ @param key=None: a dict containing wave_id, wavelet_id and email
+ @param session=None: the parent session object
+ @param new_permission: the raw permission type to give this session
+ '''
+ if session == None:
+ session = sessionTools.get(key['wave_id'], key['wavelet_id'], key['email'])
+
+ def worker(session, new_permission):
+ '''
+ @transaction_safe
+ '''
+ settings = get(session)
+ settings.rw_permission = new_permission
+ put(settings, session.wave_id, session.wavelet_id, session.email)
+
+ db.run_in_transaction(worker, session, new_permission)
+
161 dbtools/waveTools.py
@@ -0,0 +1,161 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Methods to make using WaveTools models easier
+'''
+import base64
+
+import dbConfig
+import memcacheConfig
+from models import FollowedWave
+from models import WaveMeta
+
+from google.appengine.api import memcache
+
+def get(wave_id, wavelet_id):
+ '''
+ Fetches the WaveMeta object from the datastore using the most efficient
+ method
+ @param wave_id: the wave id of the tuple
+ @param wavelet_id: the wavelet id of the tuple
+ @return the WaveMeta object or None if it could not be found
+ '''
+ followedWave = _getFollowedWave(wave_id, wavelet_id)
+ if followedWave == None:
+ return None
+ return _getWaveMeta(followedWave)
+
+def put(waveMeta, wave_id, wavelet_id):
+ '''
+ Places the waveMeta into the datastore
+ @param waveMeta: the waveMeta object to place
+ @param wave_id: the wave id the tuple relates to
+ @param wavelet_id: the wavelet id the tuple relates to
+ '''
+ _putWaveMeta(waveMeta, wave_id, wavelet_id)
+
+def createOrUpdate(wave_id, wavelet_id, participant_profiles=None):
+ '''
+ Creates or updates a followed wave and wave meta object
+ @param wave_id: the id of the wave these records are for
+ @param wavelet_id: the id of the wavelet these records are for
+ @param participant_profiles=None: the participant profiles for this wave
+ '''
+ #Fetch or create
+ waveMeta = get(wave_id, wavelet_id)
+ if not waveMeta:
+ followedWave = FollowedWave(wave_id = wave_id,
+ wavelet_id = wavelet_id,
+ key_name = _generateFollowedWaveKey( wave_id,
+ wavelet_id))
+ _putFollowedWave(followedWave)
+ waveMeta = WaveMeta(parent = followedWave)
+
+ if participant_profiles:
+ waveMeta.participant_profiles = participant_profiles
+
+ put(waveMeta, wave_id, wavelet_id)
+
+def _getFollowedWave(wave_id, wavelet_id):
+ '''
+ Returns a followed wave if it can be found in the datastore or memcache
+ @param wave_id: the wave id of the database entry
+ @param wavelet_id: the wavelet id of the database entry
+ @return the followed wave instance, or None if it was not found
+ '''
+ key = base64.b64encode( memcacheConfig.PREFIX['FOLLOWED_WAVE'] +
+ wave_id + wavelet_id)
+ followedWave = memcache.get(key)
+ if not followedWave == None:
+ return followedWave
+ else:
+ followedWave = FollowedWave.get_by_key_name(
+ _generateFollowedWaveKey(wave_id, wavelet_id)
+ )
+ memcache.add(key, followedWave, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
+ return followedWave
+
+def _generateFollowedWaveKey(wave_id, wavelet_id):
+ '''
+ Generates a key for a followed wave instance
+ @param wave_id: the id of the wave this model represents
+ @param wavelet_id: the id of the wavelet this model represents
+ '''
+ return dbConfig.KEY_PREFIX["FOLLOWED_WAVE"] + wave_id + "|" + wavelet_id
+
+def _getWaveMeta(followedWave):
+ '''
+ Returns a wave meta instance if it can be found in the datastore or
+ memcache
+ @transaction_safe
+ @param followedWave: the parent followedWave instance
+ @return the WaveMeta instance or None if it was not found
+ '''
+ key = base64.b64encode( memcacheConfig.PREFIX['WAVE_META'] +
+ followedWave.wave_id +
+ followedWave.wavelet_id)
+ waveMeta = memcache.get(key)
+ if not waveMeta == None:
+ return waveMeta
+ else:
+ query = WaveMeta.all()
+ query.ancestor(followedWave)
+ waveMeta = query.get()
+ memcache.add(key, waveMeta, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
+ return waveMeta
+
+def _putFollowedWave(followedWave):
+ '''
+ Puts the followed wave into the datastore clearing memcache etc
+ @param followedWave: the followedWave instance to add to the datastore
+ '''
+ followedWave.put()
+ memcache.delete(base64.b64encode( memcacheConfig.PREFIX['FOLLOWED_WAVE'] +
+ followedWave.wave_id +
+ followedWave.wavelet_id))
+
+def _putWaveMeta(waveMeta, wave_id, wavelet_id):
+ '''
+ Puts the WaveMeta into the datastore clearing memcache etc
+ @param waveMeta: the waveMeta to place in the datastore
+ @param wave_id: the wave_id this tuple relates to
+ @param wavelet_id: the wavelet id this tuple relates to
+ '''
+ waveMeta.put()
+ memcache.delete(base64.b64encode( memcacheConfig.PREFIX['WAVE_META'] +
+ wave_id + wavelet_id))
+
+def updateParticipantProfiles(participant_profiles, wave_id, wavelet_id):
+ '''
+ Updates the participants profiles in the WaveMeta.
+ @param participant_profiles: the new participant profiles data to add to
+ the model
+ @param wave_id: the wave id of the parent FollowedWave object
+ @param wavelet_id: the wavelet id of the parent FollowedWave object
+ '''
+ followedWave = _getFollowedWave(wave_id, wavelet_id)
+
+ def worker(followedWave, participant_profiles):
+ '''
+ @transaction_safe
+ '''
+ waveMeta = _getWaveMeta(followedWave)
+ waveMeta.participant_profiles = participant_profiles
+ _putWaveMeta(waveMeta, followedWave.wave_id, followedWave.wavelet_id)
+
+ if not followedWave == None:
+ db.run_in_transaction(worker, waveMeta, participant_profiles)
246 emailInterface.py
@@ -0,0 +1,246 @@
+'''
+Methods used in deploying emails
+'''
+import datetime
+import logging
+
+import config
+from dbtools import waveTools
+
+from google.appengine.api import mail
+
+def sendFirstNotificationEmail(url, wave_id, wavelet_id, send_to, who_modified, wave_title, message=""):
+ '''
+ Sends the first notification email to the user
+ @param url: this users unique url
+ @param wave_id: the id of the wave that the email is about
+ @param wavelet_id: the id of the wavelet that the email is about
+ @param send_to: the email receipient to sent the email to
+ @param who_modified: who modified the wave and triggered the email
+ @param wave_title: the title of the wave
+ @param message="": the personalized message that was sent by the adder
+ '''
+ if _isEmailValid(send_to):
+ logging.info("Sending first notification email to " + send_to)
+ #Fetch the meta wave object
+ metaWave = waveTools.get(wave_id, wavelet_id)
+
+ #Sort the message content variables for sending
+ wave_title = wave_title or "Untitled"
+ message = message or "No message was left"
+ display_name = _getDisplayName(metaWave, who_modified)
+ invitor = display_name + " (" + who_modified + ")"
+
+ text_variables = { 'title' : wave_title,
+ 'invitor' : invitor,
+ 'message' : message,
+ 'url' : url,
+ 'time' : datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S'),
+ 'robot_web' : config.ROBOT_WEB}
+
+ #Generate the address and subject
+ sender_address = config.ROBOT_EMAIL_SENDER_NAME + " <" + config.ROBOT_EMAIL_SEND_NOTIFICATION + ">"
+ subject = "Invitation to join: " + wave_title
+
+ #Send!
+ mail.send_mail( sender_address,
+ send_to,
+ subject,
+ FIRST_NOTIFICATION_PLAIN % text_variables,
+ html=FIRST_NOTIFICATION_HTML % text_variables)
+ logging.info("Mail sent successfully to " + send_to)
+
+
+def sendNotificationEmail(url, wave_id, wavelet_id, send_to, who_modified, wave_title, who_modified_display=None):
+ '''
+ Sends a notification email to the user
+ @param url: this users unique url
+ @param wave_id: the id of the wave that the email is about
+ @param wavelet_id: the id of the wavelet that the email is about
+ @param send_to: the email receipient to sent the email to
+ @param who_modified: who modified the wave and triggered the email
+ @param wave_title: the title of the wave
+ @param who_modified_display=None: a friendly name of who modified the wave. If None then a friendly name is retrieved from wave meta
+ '''
+ if _isEmailValid(send_to):
+ logging.info("Sending notification email to " + send_to)
+ #Fetch the meta wave object
+ metaWave = waveTools.get(wave_id, wavelet_id)
+
+ #Sort the message content variables for sending
+ wave_title = wave_title or "Untitled"
+ display_name = who_modified_display or _getDisplayName(metaWave, who_modified)
+ invitor = display_name + " (" + who_modified + ")"
+
+ text_variables = { 'title' : wave_title,
+ 'modifier' : invitor,
+ 'url' : url,
+ 'time' : datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S'),
+ 'robot_web' : config.ROBOT_WEB}
+
+ #Generate the address and subject
+ sender_address = config.ROBOT_EMAIL_SENDER_NAME + " <" + config.ROBOT_EMAIL_SEND_NOTIFICATION + ">"
+ subject = "Update: " + wave_title
+
+ mail.send_mail( sender_address,
+ send_to,
+ subject,
+ REPLY_NOTIFICATION_PLAIN % text_variables,
+ html=REPLY_NOTIFICATION_HTML % text_variables)
+ logging.info("Mail sent successfully to " + send_to)
+
+def _getDisplayName(metaWave, who_modified):
+ '''
+ @param metaWave: a metaWave object from the datastore
+ @param who_modified: the person who modified the message
+ @return the friendly name or who_modified if not found
+ '''
+ try:
+ return metaWave.participant_profiles.get(who_modified, None).get('displayName', None) or who_modified
+ except:
+ return who_modified
+
+def _isEmailValid(email):
+ '''
+ Performs some validation checks on the email address. This could be used
+ to prevent blacklisted address' in the future
+ @param email: the email address to check
+
+ @return True if and only if the email address is valid
+ '''
+ return mail.is_email_valid(email)
+
+
+
+
+################################################################################
+# Email content (HTML)
+################################################################################
+FIRST_NOTIFICATION_HTML = \
+"""
+<table width="100%%" border="0" cellspacing="0" bordercolor="gray">
+ <tr><td>
+ <table width="100%%" border="0" cellspacing="10" style="font-family:arial, sans-serif; font-size:small;">
+ <tr>
+ <td width="77px" height="77px">
+ <img src="%(robot_web)sweb/media/icon.png" title="Mr Ray logo" alt="Mr Ray logo" height="75" width="75" style="border:1px solid #CAD0D9; font-size:xx-small;"/>
+ </td>
+ <td>
+ <p style="font-size:medium; font-weight:bold;">Mr Ray, the wav-e-mail bot</p>
+ </td>
+ </tr>
+ <tr>
+ <td colspan=2><p><b>You have been invited to take part in a conversation on Google Wave using the Mr-Ray service. This means you don't need a Google Wave account. All you have to do is click on the link provided and get started!</b></p><br /></td>
+ </tr>
+ <tr>
+ <td style="color:gray;">Wave:</td><td>%(title)s</td>
+ </tr>
+ <tr>
+ <td style="color:gray;">By:</td><td>%(invitor)s</td>
+ </tr>
+ <tr>
+ <td style="color:gray;">Invitation Message:</td><td>%(message)s</td>
+ </tr>
+ <tr>
+ <td style="color:gray;">Your link:</td><td>Please don't share <a href="%(url)s">your secret link!</a></td>
+ </tr>
+ </table>
+ </td></tr>
+ <tr><td style="color:gray; font-family:arial, sans-serif; font-size:xx-small; background-color:#F6F6F6">
+ <p><b>What is Mr-Ray and why have I been sent this e-mail?</b></p>
+ <p>Mr-Ray is a free service that allows you to communicate with Google Wave users without needing an account. Someone on Google Wave wanted to invite you into their conversation. You can find more details about <a href="http://wave.google.com/about.html">Google Wave</a> and the <a href="https://github.com/waveto/mr-ray-open">Mr-Ray</a> service using the links provided.</p>
+ <p><b>Why shouldn't I share the link that was sent to me?</b><p>
+ <p>This link is unique to you and your e-mail address. Sharing it will allow other people to reply as you.</p>
+ <p><b>I don't want any more notifications about this wave, what should I do?</b></p>
+ <p>Don't worry. Just ignore this e-mail. You will only receive more notifications if you visit the link we provided.</p>
+ <br />
+ <p>Mail sent at %(time)s</p>
+ <p>Do not reply to this email address it is not monitored. You will not receive any new notifications about updates to the wave until you have visited the url.</p>
+ </td></tr>
+</table>
+"""
+
+REPLY_NOTIFICATION_HTML = \
+"""
+<table width="100%%" border="0" cellspacing="0" bordercolor="gray">
+ <tr><td>
+ <table width="100%%" border="0" cellspacing="10" style="font-family:arial, sans-serif; font-size:small;">
+ <tr>
+ <td width="77px" height="77px">
+ <img src="%(robot_web)sweb/media/icon.png" title="Mr Ray logo" alt="Mr Ray logo" height="75" width="75" style="border:1px solid #CAD0D9; font-size:xx-small;"/>
+ </td>
+ <td>
+ <p style="font-size:medium; font-weight:bold;">Mr Ray, the wav-e-mail bot</p>
+ </td>
+ </tr>
+ <tr>
+ <td colspan=2><p><b>A Wave that you follow has been updated. We thought you might want to see the changes!</b></p><br /></td>
+ </tr>
+ <tr>
+ <td style="color:gray;">Wave:</td><td>%(title)s</td>
+ </tr>
+ <tr>
+ <td style="color:gray;">By:</td><td>%(modifier)s</td>
+ </tr>
+ <tr>
+ <td style="color:gray;">Your link:</td><td>Please don't share <a href="%(url)s">your secret link!</a></td>
+ </tr>
+ </table>
+ </td></tr>
+ <tr><td style="color:gray; font-family:arial, sans-serif; font-size:xx-small; background-color:#F6F6F6">
+ <p><b>Why shouldn't I share the link that was sent to me?</b><p>
+ <p>This link is unique to you and your e-mail address. Sharing it will allow other people to reply as you.</p>
+ <p><b>I don't want any more notifications about this wave, what should I do?</b></p>
+ <p>Don't worry. Just ignore this e-mail. You will only receive more notifications if you visit the link we provided.</p>
+ <br />
+ <p>Mail sent at %(time)s</p>
+ <p>Do not reply to this email address it is not monitored. You will not receive any new notifications about updates to the wave until you have visited the url.</p>
+ </td></tr>
+</table>
+"""
+
+################################################################################
+# Email content (Plain)
+################################################################################
+FIRST_NOTIFICATION_PLAIN = \
+"""
+You have been invited to take part in a conversation on Google Wave using the Mr-Ray service. This means you don't need a Google Wave account. All you have to do is click on the link provided and get started!
+
+Wave: %(title)s
+By: %(invitor)s
+Invitation Message: %(message)s
+Your link: Please don't share your secret link: %(url)s
+
+
+************************
+*What is Mr-Ray and why have I been sent this e-mail?
+Mr-Ray is a free service that allows you to communicate with Google Wave users without needing an account. Someone on Google Wave wanted to invite you into their conversation. You can find more details about Google Wave(http://wave.google.com/about.html) and the Mr-Ray service(https://github.com/waveto/mr-ray-open) service using the links provided.
+*Why shouldn't I share the link that was sent to me?
+This link is unique to you and your e-mail address. Sharing it will allow other people to reply as you.
+*I don't want any more notifications about this wave, what should I do?
+Don't worry. Just ignore this e-mail. You will only receive more notifications if you visit the link we provided.
+
+
+Mail sent at %(time)s
+Do not reply to this email address it is not monitored. You will not receive any new notifications about updates to the wave until you have visited the url.
+"""
+
+REPLY_NOTIFICATION_PLAIN = \
+"""
+A Wave that you follow has been updated. We thought you might want to see the changes!
+
+Wave: %(title)s
+By: %(modifier)s
+Your link: Please don't share your secret link: %(url)s
+
+
+************************
+*Why shouldn't I share the link that was sent to me?
+This link is unique to you and your e-mail address. Sharing it will allow other people to reply as you.
+*I don't want any more notifications about this wave, what should I do?
+Don't worry. Just ignore this e-mail. You will only receive more notifications if you visit the link we provided.
+
+
+Mail sent at %(time)s
+Do not reply to this email address it is not monitored. You will not receive any new notifications about updates to the wave until you have visited the url.
+"""
19 errors/__init__.py
@@ -0,0 +1,19 @@
+#!/usr/bin/python
+
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+"""Declares the api package"""
26 errors/friendlyCodes.py
@@ -0,0 +1,26 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Set of friendly error codes that can be displayed to the user on a webpage
+'''
+CANNOT_CONNECT_TO_WAVE_ERR = "e0000"
+BOT_NOT_PARTICIPANT_ERR = "e0001"
+PERMISSION_DENIED_ERR = "e0002"
+REQUEST_DEADLINE_ERR = "e0003"
+UNKNOWN_ERR = "e0004"
+USER_DELETED_ERR = "e0005"
+INADEQUATE_PERMISSION_ERR = "e0006"
84 errors/interceptor.py
@@ -0,0 +1,84 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Decorator to intercept exceptions and handle them nicely
+'''
+import logging
+
+import friendlyCodes as eCodes
+import output as eOutput
+import rayExceptions
+
+from waveto import waveRpc
+
+from waveapi import simplejson
+
+from google.appengine.runtime import DeadlineExceededError
+
+class interceptExceptions(object):
+ '''
+ Decorator to process exceptions that can be recovered from. If an
+ exception is raised the appropriate page or error code is returned to the
+ user
+ @param function: the function to call
+ @return the function to return
+
+ @condition: the first arg must be the webapp.RequestHandler instance
+ '''
+ def __init__(self, render_page):
+ '''
+ @param render_page: set to true if this method is rendering a page,
+ false if it is answering an ajax call
+ '''
+ self.render_page = render_page
+
+ def __call__(self, function):
+ def decorated_function(*args, **kwargs):
+ handler = args[0]
+ try:
+ return function(*args, **kwargs)
+ except DeadlineExceededError:
+ logging.warn("Deadline Exceeded for request")
+ if self.render_page:
+ return eOutput.DeadlineExceeded(handler).RenderPage(eCodes.REQUEST_DEADLINE_ERR)
+ else:
+ return eOutput.DeadlineExceeded(handler).ReturnResponse()
+ except waveRpc.DownloadException:
+ logging.warn("Could not download wave from google servers")
+ if self.render_page:
+ return eOutput.WaveRpcDownloadProblem(handler).RenderPage(eCodes.CANNOT_CONNECT_TO_WAVE_ERR)
+ else:
+ return eOutput.WaveRpcDownloadProblem(handler).ReturnResponse()
+ except waveRpc.NotParticipantException:
+ logging.warn("Mr-Ray not participant of wave")
+ if self.render_page:
+ return eOutput.RayNotWaveParticipant(handler).RenderPage(eCodes.BOT_NOT_PARTICIPANT_ERR)
+ else:
+ return eOutput.RayNotWaveParticipant(handler).ReturnResponse()
+ except simplejson.decoder.JSONDecodeError:
+ logging.warn("Could not decode incoming json")
+ return eOutput.JsonDecodingProblem(handler).ReturnResponse()
+ except rayExceptions.MalformedRequest:
+ logging.warn("The request was malformed in some way")
+ return eOutput.MalformedRequest(handler).ReturnResponse()
+ except Exception, ex:
+ logging.exception("Unknown error")
+ if self.render_page:
+ return eOutput.UnknownProblem(handler).RenderPage(eCodes.UNKNOWN_ERR)
+ else:
+ return eOutput.UnknownProblem(handler).ReturnResponse()
+ return decorated_function
245 errors/output.py
@@ -0,0 +1,245 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Collection of classes that write out error pages or error codes
+'''
+import os
+
+import config
+
+from google.appengine.ext.webapp import template
+
+class AuthenticationDenied:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/denied.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(401)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(401)
+
+class WaveRpcDownloadProblem:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/cantcontactwave.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(502)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(502)
+
+class RayNotWaveParticipant:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/robotremoved.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(403)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(403)
+
+class DeadlineExceeded:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/standarderror.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(503)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(503)
+
+class UnknownProblem:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/standarderror.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(500)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(500)
+
+class JsonDecodingProblem:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(400)
+
+class InadequatePermission:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/inadequatepermission.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(401)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(401)
+
+class UserDeleted:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def RenderPage(self, error_code):
+ '''
+ Renders a page that informs the user the page could not be found or
+ that validation failed
+ @param error_code: the error code to add to the page
+ '''
+ self.handler.response.clear()
+ path = os.path.join(os.path.dirname(__file__), '../templates/userdeleted.html')
+ self.handler.response.out.write(template.render(path, {'robot_web': config.ROBOT_WEB, 'error_code': error_code}))
+ self.handler.response.set_status(403)
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(403)
+
+class MalformedRequest:
+
+ def __init__(self, handler):
+ '''
+ @param handler: the request handler for to return the error through
+ '''
+ self.handler = handler
+
+ def ReturnResponse(self):
+ '''
+ Returns the response code that indicates the user is not authorized
+ to view this page
+ '''
+ self.handler.response.clear()
+ self.handler.response.set_status(400)
24 errors/rayExceptions.py
@@ -0,0 +1,24 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+class MalformedRequest(Exception):
+ '''
+ Indicates that a request was malformed
+ '''
+ def __init__(self, value):
+ self.parameter = value
+ def __str__(self):
+ return repr(self.parameter)
389 gadgetHandler.py
@@ -0,0 +1,389 @@
+'''
+Copyright 2011 Acknack Ltd
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+
+'''
+Methods that handle the interaction between gadgets and robot
+'''
+import base64
+import logging
+
+import config
+from dbtools import sessionTools
+from dbtools import settingsTools
+from dbtools import waveTools
+import emailInterface
+from permission import rawTypes as pt_raw
+from security import sessionCreation
+import utils
+
+from waveapi import simplejson
+
+from google.appengine.api import mail
+from google.appengine.ext import deferred
+
+
+def onUserChangesSettings(event, wavelet, add_gadget):
+ '''
+ Deals with version two of the add participants gadget changing. Changes
+ public settings etc
+ @param event: the event that triggered the gadget state change
+ @param wavelet: the wavelet the gadget lives in
+ @param add_gadget: the add participants gadget retrieved from the wave
+ '''
+ logging.info("Gadget state changed (v2)")
+ gadgetWrapper = addParticipantsGadgetWrapper(add_gadget)
+
+ #Process incoming requests
+ incomingRequests = gadgetWrapper.getIncomingRequests()
+ logging.info("Found " + str(len(incomingRequests)) + " requests")
+ for user, request in incomingRequests.items():
+ action = request.get("action", None)
+ if action == "addEmail":
+ _addEmailUser(event, wavelet, gadgetWrapper, user, request)
+ elif action == "deleteEmail":
+ _deleteEmailUser(wavelet, gadgetWrapper, user, request)
+ elif action == "changePublic":
+ _changePublicSettings(wavelet, gadgetWrapper, user, request)
+
+ #Process incoming participant profiles
+ _saveParticipantProfiles(wavelet, gadgetWrapper)
+
+ #Write changes back to gadget
+ gadgetWrapper.reconstructGadgetState()
+
+def _saveParticipantProfiles(wavelet, gadgetWrapper):
+ '''
+ Saves the participant profiles state to the datastore
+ @param wavelet: the wavelet with the gadget
+ @param gadgetWrapper: the object wrapping the gadgets state
+ '''
+ if gadgetWrapper.getParticipantDetailsState() == "updated":
+ participantDetails = gadgetWrapper.getParticipantDetails()
+ waveMeta = waveTools.createOrUpdate( wavelet.wave_id,
+ wavelet.wavelet_id,
+ participant_profiles=participantDetails)
+ gadgetWrapper.setParticipantDetailsState(None)
+
+def _addEmailUser(event, wavelet, gadgetWrapper, user, request):
+ '''
+ Adds an email particpant to the wave and updates the gadget to reflect
+ @param event: the event that triggered the changed gadget
+ @param wavelet: the wavelet where the request originated from
+ @param user: the user that made the request
+ @param gadgetWrapper: the object that wraps this gadgets state
+ @param request: the request to process
+ '''
+ logging.info("Add email user request")
+ email = request.get('params').get("email") or None
+ message = request.get('params').get('message') or ""
+
+ if email:
+ logging.info("Creating new session for " + email)
+ url = sessionCreation.generateNewUser( wavelet.wave_id,
+ wavelet.wavelet_id,
+ email,
+ pt_raw.RW['READ_WRITE'])
+ deferred.defer(
+ emailInterface.sendFirstNotificationEmail,
+ url,
+ wavelet.wave_id,
+ wavelet.wavelet_id,
+ email,
+ event.modified_by,
+ wavelet.title,
+ message=message)
+
+ wavelet.add_proxying_participant(utils.getProxyForFromEmail(email))
+ gadgetWrapper.addEmailParticipant(email)
+ gadgetWrapper.deleteIncomingRequest(user)
+
+def _deleteEmailUser(wavelet, gadgetWrapper, user, request):
+ '''
+ Removes an email participant from the wave and updates the gadget to reflect
+ @param wavelet: the wavelet where the request originated from
+ @param user: the user that made the request
+ @param gadgetWrapper: the object that wraps this gadgets state
+ @param request: the request to process
+ '''
+ logging.info("Delete email user request")
+ email = request.get('params').get("email") or None
+ if email:
+ logging.info("Deleting " + email)
+ settingsTools.changeRWPermission( pt_raw.RW['DELETED'],
+ key={ 'wave_id' : wavelet.wave_id,
+ 'wavelet_id': wavelet.wavelet_id,
+ 'email' : email})
+ gadgetWrapper.removeEmailParticipant(email)
+ gadgetWrapper.deleteIncomingRequest(user)
+
+
+def _changePublicSettings(wavelet, gadgetWrapper, user, request):
+ '''
+ Changes the public settings for the wave and updates the gadget to reflect
+ @param wavelet: the wavelet where the request originated from
+ @param user: the user that made the request
+ @param gadgetWrapper: the object that wraps this gadgets state
+ @param request: the request to process
+ '''
+ logging.info("Change public settings request")
+ #Extract values from the incoming json
+ isPublic = None
+ isReadOnly = None
+ params = request.get("params", None)
+ if params:
+ isPublic = params.get("isPublic", None)
+ isReadOnly = params.get("isReadOnly", None)
+ if isPublic == None:
+ isPublic = False
+ if isReadOnly == None:
+ isReadOnly = True
+
+ #Convert values into permissions
+ if isReadOnly:
+ rw_permission = pt_raw.RW['READ']
+ else:
+ rw_permission = pt_raw.RW['READ_WRITE']
+ if not isPublic:
+ rw_permission = pt_raw.RW['DELETED']
+ url = sessionCreation.generateNewUser( wavelet.wave_id,
+ wavelet.wavelet_id,
+ config.PUBLIC_EMAIL,
+ rw_permission)
+ gadgetWrapper.changePublicSettings(isPublic, isReadOnly, url)
+ gadgetWrapper.deleteIncomingRequest(user)
+
+
+def constructInitialState(wavelet):
+ '''
+ Constructs the initial gadget state. This is used purely for migration from
+ the v1 gadget to v2 gadget. So it returns a list of email users in the
+ correct format for the gadget
+ @param wavelet: the wavelet where the gadget will live
+ @return a dictionary containing the key values of the initial state
+ '''
+ sessions = sessionTools.fetch(wavelet.wave_id, wavelet.wavelet_id)
+ #Form the email list
+ email_list = []
+ public_session = None
+ for session in sessions:
+ if sessionTools.isPublic(session):
+ public_session = session
+ else:
+ email_list.append(session.email)
+
+ #Form public settings
+ public = {}
+ isPublic = False
+ isReadOnly = True
+
+ try:
+ public_settings = settingsTools.get(public_session)
+ rw_permission = public_settings.rw_permission
+
+ if rw_permission == pt_raw.RW['READ']:
+ isPublic = True
+ isReadOnly = True
+ elif rw_permission == pt_raw.RW['READ_WRITE']:
+ isPublic = True
+ isReadOnly = False
+ except:
+ #Just means public settings could not be found. Defaults will be used
+ pass
+ public.update({'isPublic' : isPublic, 'isReadOnly' : isReadOnly});
+
+ output = base64.b64encode(simplejson.dumps({'emailParticipants' : email_list,
+ 'public' : public}))
+ return {'state' : output, 'participantDetailsState' : 'fetch'}
+
+def requestParticipantProfilesUpdate(add_gadget):
+ '''
+ Sends a request to the gadget to resend the participant profiles
+ @param add_gadget: the gadget found in this wave
+ '''
+ add_gadget.update_element({'participantDetailsState' : 'fetch'})
+
+def onAddParticipantsChangedV1(event, wavelet, add_gadget):
+ '''
+ Deals with the add participants gadget changing, subscribes wave users etc
+ @param event: the event that triggered the gadget state change
+ @param wavelet: the wavelet the gadget lives in
+ @param add_gadget: the add participants gadget retrieved from the wave
+ '''
+
+ #Fetch the values from the gadget
+ participants_json = add_gadget.get("EMAIL-PARTICIPANTS", None)
+ if participants_json:
+ participants_json = base64.b64decode(participants_json)
+ else:
+ participants_json = "[]"
+ participants = simplejson.loads(participants_json)
+ new_participant = add_gadget.get("ADD-PARTICIPANT", None)
+
+ if new_participant:
+ logging.info("Subscribing new e-mail user: " + new_participant)
+ #Check the email address appears valid. Fail silently if not. The js
+ #should check and report errors before sending. This prevents hackers
+ if not mail.is_email_valid(new_participant):
+ logging.info(new_participant + " not subscribed. E-mail address not valid")
+ return
+
+ #Only update if the user is new
+ if not new_participant in participants:
+ deferred.defer(
+ emailInterface.sendFirstNotificationEmail,
+ sessionCreation.generateNewUser(wavelet.wave_id,
+ wavelet.wavelet_id,
+ new_participant,
+ pt_raw.RW['READ_WRITE']),
+ wavelet.wave_id,
+ wavelet.wavelet_id,
+ new_participant,
+ event.modified_by,
+ wavelet.title)
+
+ participants.append(new_participant)
+ wavelet.add_proxying_participant(utils.getProxyForFromEmail(new_participant))
+
+ #Update the gadget
+ participants_json = simplejson.dumps(participants)
+ add_gadget.update_element({ "ADD-PARTICIPANT": None,
+ "EMAIL-PARTICIPANTS": base64.b64encode(participants_json)})
+
+
+class addParticipantsGadgetWrapper:
+ '''
+ Object that models the add participants gadget in a pythonic way
+ '''
+ def __init__(self, gadget):
+ '''
+ @param gadget: the gadget instance
+ '''
+ self._gadget = gadget
+ self._default_state = {"emailParticipants" : [], 'public':{'isPublic':False, 'isReadOnly':True}}
+ self._parseGadgetState()
+
+ def _loads(self, obj):
+ '''
+ Loads an object from the gadget state if it is b64/json
+ @param obj: the raw string to load
+ @return the python object
+ '''
+ if not obj:
+ return None
+ return simplejson.loads(base64.b64decode(obj))
+
+ def _dumps(self, obj):
+ '''
+ Writes an object to a string so it can be stored in the gadget state
+ @param obj: the object to write to string
+ @return a b64/json string representing the object
+ '''
+ if not obj:
+ return ""
+ return base64.b64encode(simplejson.dumps(obj))
+
+ def _parseGadgetState(self):
+ '''
+ Parses the state variable into a python data structure and stores in
+ the object
+ '''
+ self._participantDetails = self._loads(self._gadget.get("participantDetails", None)) or {}
+ self._state = self._loads(self._gadget.get("state", None)) or {}
+ self._participantDetailsState = self._gadget.get("participantDetailsState", None)
+ self._parseIncomingRequests()
+
+ def _parseIncomingRequests(self):
+ '''
+ Parses the incoming requests and stores in the object
+ '''