src/cm/api/handlers.py
changeset 287 fc5ed157ebfe
child 288 c6fe4822a243
equal deleted inserted replaced
282:b5deb8e32219 287:fc5ed157ebfe
       
     1 from piston.handler import AnonymousBaseHandler, BaseHandler
       
     2 from piston.utils import rc
       
     3 
       
     4 from cm.models import Text,TextVersion, Role, UserRole
       
     5 from cm.views import get_keys_from_dict, get_textversion_by_keys_or_404, get_text_by_keys_or_404, get_textversion_by_keys_or_404, redirect
       
     6 from cm.security import get_texts_with_perm, has_perm, get_viewable_comments, \
       
     7     has_perm_on_text_api
       
     8 from cm.security import get_viewable_comments
       
     9 from cm.utils.embed import embed_html
       
    10 from cm.views.create import CreateTextContentForm, create_text
       
    11 from piston.utils import validate
       
    12 from settings import SITE_URL
       
    13 
       
    14 URL_PREFIX = SITE_URL + '/api'
       
    15  
       
    16 class AnonymousTextHandler(AnonymousBaseHandler):
       
    17     type = "Text methods"
       
    18     title = "Read text info"
       
    19     fields = ('key', 'title', 'format', 'content', 'created', 'modified', 'nb_comments', 'nb_versions', 'embed_html', ('last_text_version', ('created','modified', 'format', 'title', 'content')))   
       
    20     allowed_methods = ('GET', )   
       
    21     model = Text
       
    22     desc = """ Read text identified by `key`."""
       
    23     args = None
       
    24 
       
    25     @staticmethod
       
    26     def endpoint():
       
    27         return URL_PREFIX + '/text/{key}/'
       
    28 
       
    29 
       
    30     @has_perm_on_text_api('can_view_text')
       
    31     def read(self, request, key):
       
    32         
       
    33         text = get_text_by_keys_or_404(key)
       
    34         setattr(text,'nb_comments',len(get_viewable_comments(request, text.last_text_version.comment_set.all(), text)))
       
    35         setattr(text,'nb_versions',text.get_versions_number())
       
    36         setattr(text,'embed_html',embed_html(text.key))
       
    37 
       
    38         return text
       
    39 
       
    40 class TextHandler(BaseHandler):
       
    41     type = "Text methods"    
       
    42     anonymous = AnonymousTextHandler
       
    43     allowed_methods = ('GET',)  
       
    44     no_display = True 
       
    45 
       
    46 class AnonymousTextVersionHandler(AnonymousBaseHandler):
       
    47     type = "Text methods"
       
    48     title = "Read text version info"
       
    49     fields = ('key', 'title', 'format', 'content', 'created', 'modified', 'nb_comments',)   
       
    50     allowed_methods = ('GET', )   
       
    51     model = Text
       
    52     desc = """ Read text version identified by `version_key` inside text identified by `key`."""
       
    53     args = None
       
    54 
       
    55     @staticmethod
       
    56     def endpoint():
       
    57         return URL_PREFIX + '/text/{key}/{version_key}/'
       
    58 
       
    59 
       
    60     @has_perm_on_text_api('can_view_text')
       
    61     def read(self, request, key, version_key):
       
    62         text_version = get_textversion_by_keys_or_404(version_key, key=key)
       
    63         setattr(text_version,'nb_comments',len(get_viewable_comments(request, text_version.comment_set.all(), text_version.text)))
       
    64 
       
    65         return text_version
       
    66 
       
    67 class TextVersionHandler(BaseHandler):
       
    68     type = "Text methods"    
       
    69     anonymous = AnonymousTextVersionHandler
       
    70     allowed_methods = ('GET',)  
       
    71     no_display = True 
       
    72 
       
    73 class AnonymousTextListHandler(AnonymousBaseHandler):
       
    74     title = "List texts"    
       
    75     type = "Text methods"    
       
    76     fields = ('key', 'title', 'created', 'modified', 'nb_comments', 'nb_versions',)   
       
    77     allowed_methods = ('GET',)   
       
    78     model = Text
       
    79     desc = """Lists texts on workspace."""        
       
    80 
       
    81     @staticmethod
       
    82     def endpoint():
       
    83         return URL_PREFIX + '/text/'
       
    84 
       
    85     def read(self, request):
       
    86         order_by = '-id'
       
    87         texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by)        
       
    88         return texts
       
    89 
       
    90 class TextListHandler(BaseHandler):
       
    91     title = "Create text"    
       
    92     type = "Text methods"    
       
    93     allowed_methods = ('POST', )    
       
    94     anonymous = AnonymousTextListHandler
       
    95     desc = "Create a text with the provided parameters."
       
    96     args = """<br/>
       
    97 `title`: title of the text<br/>
       
    98 `format`: format content ('markdown', 'html')<br/>
       
    99 `content`: content (in specified format)<br/>
       
   100 `anon_role`: role to give to anon users: null, 4: commentator, 5: observer<br/>
       
   101         """
       
   102      
       
   103     @staticmethod
       
   104     def endpoint():
       
   105         return URL_PREFIX + '/text/'
       
   106 
       
   107     def create(self, request):
       
   108         form = CreateTextContentForm(request.POST)
       
   109         if form.is_valid():
       
   110             text = create_text(request.user, form.cleaned_data)
       
   111             anon_role = request.POST.get('anon_role', None)
       
   112             if anon_role:
       
   113                 userrole = UserRole.objects.create(user=None, role=Role.objects.get(id=anon_role), text=text)         
       
   114             return {'key' : text.key , 'version_key' : text.last_text_version.key, 'created': text.created}
       
   115         else:
       
   116             resp = rc.BAD_REQUEST
       
   117         return resp
       
   118 
       
   119 from cm.exception import UnauthorizedException
       
   120 from cm.views.texts import text_delete
       
   121 
       
   122 class TextDeleteHandler(BaseHandler):
       
   123     type = "Text methods"
       
   124     allowed_methods = ('POST', )    
       
   125     title = "Delete text"    
       
   126     desc = "Delete the text identified by `key`."
       
   127 
       
   128     @staticmethod
       
   129     def endpoint():
       
   130         return URL_PREFIX + '/text/{key}/delete/'
       
   131 
       
   132     def create(self, request):
       
   133         """
       
   134         Delete text identified by `key`.
       
   135         """
       
   136         try:
       
   137             key = request.POST.get('key')
       
   138             text_delete(request, key=key)
       
   139         except UnauthorizedException:
       
   140             return rc.FORBIDDEN
       
   141         except KeyError:
       
   142             return rc.BAD_REQUEST
       
   143         return rc.DELETED
       
   144 
       
   145 from cm.views.texts import text_pre_edit
       
   146  
       
   147 class TextPreEditHandler(BaseHandler):
       
   148     type = "Text methods"
       
   149     allowed_methods = ('POST', )    
       
   150     title = "Ask for edit impact"    
       
   151     desc = "Returns the number of impacted comments."
       
   152     args = """<br />
       
   153 `new_format`: new format content ('markdown', 'html')<br />        
       
   154 `new_content`: new content (in specified format)<br />    
       
   155     """ 
       
   156 
       
   157     @staticmethod
       
   158     def endpoint():
       
   159         return URL_PREFIX + '/text/{key}/pre_edit/'
       
   160     
       
   161     def create(self, request, key):
       
   162         return text_pre_edit(request, key=key)
       
   163 
       
   164 from cm.views.texts import text_edit
       
   165     
       
   166 class TextEditHandler(BaseHandler):
       
   167     allowed_methods = ('POST', )    
       
   168     type = "Text methods"
       
   169     title = "Edit text"    
       
   170     desc = "Update text identified by `key`."
       
   171     args = """<br />
       
   172 `title`: new title of the text<br />
       
   173 `format`: new format content ('markdown', 'html')<br />
       
   174 `content`: new content (in specified format)<br />
       
   175 `note`: note to add to edit<br />
       
   176 `new_version`: boolean: should a new version of the text be created?<br />
       
   177 `keep_comments`: boolean: should existing comments be keep (if possible)?<br />
       
   178     """ 
       
   179     
       
   180     @staticmethod
       
   181     def endpoint():
       
   182         return URL_PREFIX + '/text/{key}/edit/'
       
   183     
       
   184     
       
   185     def create(self, request, key):
       
   186         res = text_edit(request, key=key)
       
   187         text = get_text_by_keys_or_404(key)
       
   188         text_version = text.last_text_version
       
   189         return {'version_key' : text_version.key , 'created': text_version.created}
       
   190 
       
   191 from django.contrib.auth import authenticate
       
   192     
       
   193 class SetUserHandler(AnonymousBaseHandler):
       
   194     allowed_methods = ('POST',)    
       
   195     type = "User methods"
       
   196     title = "Set username and email"    
       
   197     desc = "Set username and email to use when commenting."
       
   198     args = """<br />
       
   199 `user_name`: user's name<br />
       
   200 `user_email`: user's email<br />
       
   201     """ 
       
   202     
       
   203     @staticmethod
       
   204     def endpoint():
       
   205         return URL_PREFIX + '/setuser/'
       
   206     
       
   207     def create(self, request):
       
   208         user_name = request.POST.get('user_name', None)
       
   209         user_email = request.POST.get('user_email', None)
       
   210         if user_name and user_email: 
       
   211             response = rc.ALL_OK
       
   212             response.set_cookie('user_name', user_name)
       
   213             response.set_cookie('user_email', user_email)
       
   214             return response
       
   215         else:
       
   216             return rc.BAD_REQUEST    
       
   217                          
       
   218 
       
   219 
       
   220 from piston.doc import documentation_view
       
   221 
       
   222 from piston.handler import handler_tracker
       
   223 from django.template import RequestContext
       
   224 from piston.doc import generate_doc
       
   225 from django.shortcuts import render_to_response
       
   226 
       
   227 def documentation(request):
       
   228     """
       
   229     Generic documentation view. Generates documentation
       
   230     from the handlers you've defined.
       
   231     """
       
   232     docs = [ ]
       
   233 
       
   234     for handler in handler_tracker:
       
   235         doc = generate_doc(handler)
       
   236         setattr(doc,'type', handler.type)
       
   237         docs.append(doc)
       
   238 
       
   239     def _compare(doc1, doc2): 
       
   240        #handlers and their anonymous counterparts are put next to each other.
       
   241        name1 = doc1.name.replace("Anonymous", "")
       
   242        name2 = doc2.name.replace("Anonymous", "")
       
   243        return cmp(name1, name2)    
       
   244  
       
   245     #docs.sort(_compare)
       
   246        
       
   247     return render_to_response('api_doc.html', 
       
   248         { 'docs': docs }, RequestContext(request))
       
   249 
       
   250 from piston.doc import generate_doc
       
   251 DocHandler = generate_doc(TextPreEditHandler)