Dodanie przycisków do zapisywania i usuwania fragmentów.
[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 class MergeRequestForm(forms.Form):
15     # should the target document revision be updated or shared
16     type = forms.ChoiceField(choices=(('update', 'Update'), ('share', 'Share')) )
17     
18     #
19     # if type == update:
20     #   * user's revision which is the base of the merge
21     # if type == share:
22     #   * revision which will be pulled to the main branch
23     #
24     # NOTE: the revision doesn't have to be owned by the user
25     #  who requests the merge:
26     #   a) Every user can update his branch
27     #   b) Some users can push their changes
28     #     -> if they can't, they leave a PRQ
29     #   c) Some users can pull other people's changes
30     #   d) Some users can update branches owned by special
31     #    users associated with PRQ's
32     revision = forms.RegexField('[0-9a-f]{40}')
33
34     # any additional comments that user wants to add to the change
35     message = forms.CharField(required=False)
36
37 class DocumentUploadForm(forms.Form):
38     ocr_file = forms.FileField(label='Source OCR file', required=False)
39     ocr_data = forms.CharField(widget=forms.HiddenInput(), required=False)
40     
41     bookname = forms.RegexField(regex=r'[0-9\.\w_-]+',  \
42         label='Publication name', help_text='Example: słowacki__beniowski__pieśń_1')
43     
44     generate_dc = forms.BooleanField(required=False, \
45         initial=True, label=u"Generate DublinCore template")
46
47
48     def clean(self):
49         clean_data = self.cleaned_data
50
51         ocr_file = clean_data['ocr_file']
52         ocr_data = clean_data['ocr_data']
53
54         if not ocr_file and not ocr_data:
55             raise forms.ValidationError(
56                 "You must either provide file descriptor or raw data." )
57
58         return clean_data
59
60 PRQ_USER_RE = re.compile(r"^\$prq-(\d{1,10})$", re.UNICODE)
61
62 class DocumentRetrieveForm(forms.Form):    
63     revision = forms.RegexField(regex=r'latest|[0-9a-z]{40}', required=False)
64     user = forms.CharField(required=False)
65         
66     def clean_user(self):
67         # why, oh why doesn't django implement this!!!
68         # value = super(DocumentRetrieveForm, self).clean_user()
69         value = self.cleaned_data['user']        
70         
71         if value.startswith('$'):
72             # library user (... maybe later)
73             if value == '$library':
74                 raise forms.ValidationError("Invalid user name '%s'" % value)
75
76             m = PRQ_USER_RE.match(value)
77             
78             if m:
79                 try:
80                     return value
81                 except:
82                     raise forms.ValidationError("User doesn't exist.")
83             raise forms.ValidationError("Invalid user name '%s'" % value)
84         try:
85             return value
86         except:
87             raise forms.ValidationError("User doesn't exist.")                
88            
89
90 class TextRetrieveForm(DocumentRetrieveForm):
91     chunk = forms.CharField(required=False)
92     format = forms.CharField(required=False)
93
94     def clean_format(self):
95         value = self.cleaned_data['format']
96         if not value:
97             return 'raw'
98
99         if value not in ('nl', 'raw'):
100             raise forms.ValidationError("Invalid text format")
101         return value
102
103 class TextUpdateForm(DocumentRetrieveForm):
104     message = forms.CharField(required=False)
105     contents = forms.CharField(required=False)
106     chunks = forms.CharField(required=False)
107
108     format = forms.CharField(required=False)
109
110     def clean_format(self):
111         value = self.cleaned_data['format']
112         if not value:
113             return 'raw'
114
115         if value not in ('nl', 'raw'):
116             raise forms.ValidationError("Invalid text format")
117         return value
118
119     def clean_message(self):
120         value = self.cleaned_data['message']
121
122         if value:
123             return u"$USER$ " + value
124         else:
125             return u"$AUTO$ XML content update."
126
127     def clean_chunks(self):
128         value = self.cleaned_data['chunks']
129
130         try:
131             return json.loads(value)
132         except Exception, e:
133             forms.ValidationError("Invalid JSON: " + e.message)
134
135
136     def clean(self):
137         if self.cleaned_data['contents'] and self.cleaned_data['chunks']:
138             raise forms.ValidationError("Pass either contents or chunks - not both ")
139
140         if not self.cleaned_data['contents'] and not self.cleaned_data['chunks']:
141             raise forms.ValidationError("You must pass contents or chunks.")
142
143         return self.cleaned_data