Merge branch 'master' of stigma:platforma
[redakcja.git] / apps / api / forms.py
1 # -*- encoding: utf-8 -*-
2
3 __author__= "Łukasz Rekucki"
4 __date__ = "$2009-09-20 21:34:52$"
5 __doc__ = "Micro-forms for the API."
6
7 from django import forms
8 from api.models import PullRequest
9 from django.contrib.auth.models import User
10
11 import re
12 from django.utils import simplejson as json
13
14
15 class MergeRequestForm(forms.Form):
16     # should the target document revision be updated or shared
17     type = forms.ChoiceField(choices=(('update', 'Update'), ('share', 'Share')) )
18     
19     #
20     # if type == update:
21     #   * user's revision which is the base of the merge
22     # if type == share:
23     #   * revision which will be pulled to the main branch
24     #
25     # NOTE: the revision doesn't have to be owned by the user
26     #  who requests the merge:
27     #   a) Every user can update his branch
28     #   b) Some users can push their changes
29     #     -> if they can't, they leave a PRQ
30     #   c) Some users can pull other people's changes
31     #   d) Some users can update branches owned by special
32     #    users associated with PRQ's
33     revision = forms.RegexField('[0-9a-f]{40}')
34
35     # any additional comments that user wants to add to the change
36     message = forms.CharField(required=False)
37
38 class DocumentUploadForm(forms.Form):
39     ocr_file = forms.FileField(label='Source OCR file', required=False)
40     ocr_data = forms.CharField(widget=forms.HiddenInput(), required=False)
41     
42     bookname = forms.RegexField(regex=r'[0-9\.\w_-]+',  \
43         label='Publication name', help_text='Example: słowacki__beniowski__pieśń_1')
44     
45     generate_dc = forms.BooleanField(required=False, \
46         initial=True, label=u"Generate DublinCore template")
47
48
49     def clean(self):
50         clean_data = self.cleaned_data
51
52         ocr_file = clean_data['ocr_file']
53         ocr_data = clean_data['ocr_data']
54
55         if not ocr_file and not ocr_data:
56             raise forms.ValidationError(
57                 "You must either provide file descriptor or raw data." )
58
59         return clean_data
60
61 PRQ_USER_RE = re.compile(r"^\$prq-(\d{1,10})$", re.UNICODE)
62
63 class DocumentRetrieveForm(forms.Form):    
64     revision = forms.RegexField(regex=r'latest|[0-9a-z]{40}', required=False)
65     user = forms.CharField(required=False)
66
67     def clean_user(self):
68         # why, oh why does django doesn't implement this!!!
69         # value = super(DocumentRetrieveForm, self).clean_user()
70         value = self.cleaned_data['user']        
71         
72         if value.startswith('$'):
73             # library user (... maybe later)
74             if value == '$library':
75                 raise forms.ValidationError("Invalid user name '%s'" % value)
76
77             m = PRQ_USER_RE.match(value)
78             
79             if m:
80                 try:
81                     return value
82                 except:
83                     raise forms.ValidationError("User doesn't exist.")
84             raise forms.ValidationError("Invalid user name '%s'" % value)
85         try:
86             return value
87         except:
88             raise forms.ValidationError("User doesn't exist.")                
89            
90
91 class TextRetrieveForm(DocumentRetrieveForm):
92     part = forms.CharField(required=False)
93
94 class TextUpdateForm(DocumentRetrieveForm):
95     message = forms.CharField(required=False)
96     contents = forms.CharField(required=False)
97     chunks = forms.CharField(required=False)
98
99     def clean_message(self):
100         value = self.cleaned_data['message']
101
102         if value:
103             return u"$USER$ " + request.POST['message']
104         else:
105             return u"$AUTO$ XML content update."
106
107     def clean_chunks(self):
108         value = self.cleaned_data['chunks']
109
110         try:
111             return json.loads(value)
112         except Exception, e:
113             forms.ValidationError("Invalid JSON: " + e.message)
114
115
116     def clean(self):
117         if self.cleaned_data['contents'] and self.cleaned_data['chunks']:
118             raise forms.ValidationError("Pass either contents or chunks - not both ")
119
120         if not self.cleaned_data['contents'] and not self.cleaned_data['chunks']:
121             raise forms.ValidationError("You must pass contents or chunks.")
122
123         return self.cleaned_data