Convert old style except blocks to except Exception as variable: blocks
[htsworkflow.git] / bcmagic / views.py
1 from django.http import HttpResponse
2 from django.template import RequestContext, Template, Context
3 from django.shortcuts import render_to_response
4 from django.core.exceptions import ObjectDoesNotExist
5
6 from . import models
7 from .utils import report_error, redirect_to_url
8 from .plugin import bcm_plugin_processor
9 from . import plugin
10 #from htsworkflow.util.jsonutil import encode_json
11
12 try:
13     import json
14 except ImportError as e:
15     import simplejson as json
16
17 import re
18
19 from htsworkflow.frontend.bcmagic import forms
20
21
22 def index(request):
23     """
24     Display a barcode magic input box
25     """
26     form = forms.BarcodeMagicForm()
27
28     return render_to_response('bcmagic/magic.html', {'bcmagic': form},
29                               context_instance=RequestContext(request))
30
31
32 def __plugin_search(text):
33     """
34     Runs registered plugins to search for results
35     """
36
37     hits = []
38     for label, search_func in plugin._SEARCH_FUNCTIONS.items():
39         result = search_func(text)
40         if result is not None:
41             hits.extend(result)
42
43     n = len(hits)
44     if n == 0:
45         msg = 'No hits found for: %s' % (text)
46         return report_error(msg)
47     elif n == 1:
48         return redirect_to_url(hits[0][1])
49     else:
50         msg = "%d hits found for (%s); multi-hit not implemented yet." % \
51               (n, text)
52         return report_error(msg)
53
54
55     #return json.dumps(hits)
56
57
58 def __magic_process(text):
59     """
60     Based on scanned text, check to see if there is map object to use
61     for a useful redirect.
62     """
63     # Split text on |
64     split_text = text.split('|')
65
66     # There should always be at least one | in a valid scan.
67     if len(split_text) <= 1:
68         #return report_error('Invalid text: %s' % (text))
69         return __plugin_search(text)
70
71     # Keyword is the first element in the list
72     keyword = split_text[0]
73
74     # Attempt to find a KeywordMap based on keyword
75     try:
76         keymap = models.KeywordMap.objects.get(keyword=keyword)
77     except ObjectDoesNotExist(e):
78         return report_error('Keyword (%s) is not defined' % (keyword))
79
80     # Remove keyword and only scan the content
81     content = '|'.join(split_text[1:])
82
83     #FIXME: would be faster to cache compiled regex
84     search = re.compile(keymap.regex)
85
86     mo = search.search(content)
87
88     # if the search was invalid
89     if not mo:
90         return report_error(
91             '(%s) failed to match (%s)' % (keymap.regex, content)
92         )
93
94     t = Template(keymap.url_template)
95     c = Context(mo.groupdict())
96
97     return redirect_to_url(str(t.render(c)))
98
99
100 def magic(request):
101     """
102     Let the magic begin
103     """
104     d = {}
105
106     #Retrieve posted text from processing
107     if 'text' in request.POST:
108         text = request.POST['text']
109     else:
110         text = None
111
112     #Retrieve bmc_mode for processing
113     if 'bcm_mode' in request.POST:
114         bcm_mode = request.POST['bcm_mode']
115     else:
116         bcm_mode = None
117
118     ################################
119     # Handle some errors
120     ################################
121
122     # Did not receive text error
123     if text is None or text.strip() == '':
124         d['mode'] = 'Error'
125         d['status'] = 'Did not recieve text'
126
127         return HttpResponse(json.dumps(d), 'text/plain')
128
129     # Did not receive bcm_mode error
130     if bcm_mode is None or bcm_mode.strip() == '':
131         d['mode'] = 'Error'
132         d['status'] = 'Missing bcm_mode information'
133
134     ################################
135     # Figure out which mode to use
136     ################################
137     keyword = text.split('|')[0]
138
139     # Handle URL mode by default
140     if keyword == 'url':
141         d['mode'] = 'redirect'
142         d['url'] = text.split('|')[1]
143
144     # Pass off processing to plugins
145     elif bcm_mode != 'default':
146         d = bcm_plugin_processor(keyword, text, bcm_mode)
147
148     # Try keyword mapper
149     else:
150         d = __magic_process(text)
151
152     return HttpResponse(json.dumps(d), 'text/plain')
153
154
155 def json_test(request):
156     d = {}
157
158     if 'text' in request.POST:
159         text = request.POST['text']
160     else:
161         text = None
162
163     #return HttpResponse(json.dumps(request.POST.items()), 'text/plain')
164     if text is None or text.strip() == '':
165         d['mode'] = 'Error'
166         d['status'] = 'Did not recieve text'
167         return HttpResponse(json.dumps(d), 'text/plain')
168
169     if text.split('|')[0] == 'url':
170         d['mode'] = 'redirect'
171         d['url'] = text.split('|')[1]
172     else:
173         d['msg'] = 'Recieved text: %s' % (text)
174         d['mode'] = 'clear'
175
176     return HttpResponse(json.dumps(d), 'text/plain')