forked from OSQA/osqa
-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathquestion.py
More file actions
1872 lines (1589 loc) · 77.2 KB
/
Copy pathquestion.py
File metadata and controls
1872 lines (1589 loc) · 77.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import logging
import operator
import regex as re
from copy import copy
from django.conf import settings as django_settings
from django.db import models
from django.db.models import Count, F, Q
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import cache # import cache, not from cache import cache, to be able to monkey-patch cache.cache in test cases
from django.core import exceptions as django_exceptions
from django.template.loader import get_template
from django.template import Context
from django.utils.translation import gettext as _
from django.utils.translation import get_language
from django.utils import timezone
import askbot
from askbot.conf import settings as askbot_settings
from askbot.models.tag import Tag, TagSynonym
from askbot.models.tag import get_tags_by_names
from askbot.models.tag import filter_accepted_tags, filter_suggested_tags
from askbot.models.tag import separate_unused_tags
from askbot.models.base import BaseQuerySetManager
from askbot.models.base import DraftContent, AnonymousContent
from askbot.models.user import Activity, Group, PERSONAL_GROUP_NAME_PREFIX
from askbot.models.fields import LanguageCodeField
from askbot import signals
from askbot import const
from askbot.utils.lists import LazyList
from askbot.utils.loading import load_plugin
from askbot.search import mysql
from askbot.utils import translation as translation_utils
from askbot.search.state_manager import DummySearchState
LOG = logging.getLogger(__name__)
def clean_tagnames(tagnames):
"""Cleans tagnames string so that the field fits the constraint of the
database.
TODO: remove this when the Thread.tagnames field is converted into
text_field
"""
tagnames = tagnames.strip().split()
# see if the tagnames field fits into 125 bytes
while True:
encoded_tagnames = ' '.join(tagnames).encode('utf-8')
length = len(encoded_tagnames)
if length == 0:
return ''
elif length <= 125:
return ' '.join(tagnames)
else:
tagnames.pop()
def default_title_renderer(thread):
"""renders thread title,
can be overridden by setting
ASKBOT_QUESTION_TITLE_RENDERER
"""
if thread.is_private():
attr = const.POST_STATUS['private']
elif thread.closed:
attr = const.POST_STATUS['closed']
elif thread.deleted:
attr = const.POST_STATUS['deleted']
else:
attr = None
if attr is not None:
return '%s %s' % (thread.title, str(attr))
else:
return thread.title
class ThreadQuerySet(models.query.QuerySet):
def get_visible(self, user):
"""filters out threads not belonging to the user groups"""
if user.is_authenticated:
groups = user.get_groups()
else:
groups = [Group.objects.get_global_group()]
return self.filter(groups__in=groups).distinct()
def get_for_title_query(self, search_query):
"""returns threads matching title query
TODO: possibly add tags
TODO: implement full text search on relevant fields
"""
if getattr(django_settings, 'ENABLE_HAYSTACK_SEARCH', False):
from askbot.search.haystack.helpers import get_threads_from_query
return self & get_threads_from_query(search_query)
else:
db_engine_name = askbot.get_database_engine_name()
filter_parameters = {'deleted': False}
if 'postgresql_psycopg2' in db_engine_name:
from askbot.search import postgresql
return postgresql.run_title_search(
self, search_query
).filter(
**filter_parameters
).order_by('-relevance')
elif 'mysql' in db_engine_name and mysql.supports_full_text_search():
filter_parameters['title__search'] = search_query
else:
filter_parameters['title__icontains'] = search_query
if askbot.is_multilingual():
filter_parameters['language_code'] = get_language()
return self.filter(**filter_parameters)
class ThreadManager(BaseQuerySetManager):
def get_queryset(self):
return ThreadQuerySet(self.model)
def get_tag_summary_from_threads(self, threads):
"""returns a humanized string containing up to
five most frequently used
unique tags coming from the ``threads``.
Variable ``threads`` is an iterable of
:class:`~askbot.models.Thread` model objects.
This is not implemented yet as a query set method,
because it is used on a list.
"""
# TODO: In Python 2.6 there is collections.Counter() thing which would be very useful here
# TODO: In Python 2.5 there is `defaultdict` which already would be an improvement
tag_counts = dict()
for thread in threads:
for tag_name in thread.get_tag_names():
if tag_name in tag_counts:
tag_counts[tag_name] += 1
else:
tag_counts[tag_name] = 1
tag_list = list(tag_counts.keys())
tag_list.sort(key=lambda t: tag_counts[t], reverse=True)
# note that double quote placement is important here
if len(tag_list) == 0:
return ''
if len(tag_list) == 1:
last_topic = '"'
elif len(tag_list) <= 5:
last_topic = _('" and "%s"') % tag_list.pop()
else:
tag_list = tag_list[:5]
last_topic = _('" and more')
return '"' + '", "'.join(tag_list) + str(last_topic)
def create(self, *args, **kwargs):
raise NotImplementedError
def create_new(self, title, author, added_at, wiki, text, tagnames=None,
is_anonymous=False, is_private=False, group_id=None,
by_email=False, email_address=None, language=None,
ip_addr=None):
"""creates new thread"""
# TODO: Some of this code will go to Post.objects.create_new
language = language or get_language()
tagnames = clean_tagnames(tagnames)
thread = super(ThreadManager, self).create(
title=title, tagnames=tagnames, last_activity_at=added_at,
last_activity_by=author, language_code=language)
# TODO: code below looks like ``Post.objects.create_new()``
from askbot.models.post import Post
question = Post(post_type='question', thread=thread, author=author,
added_at=added_at, wiki=wiki, is_anonymous=is_anonymous,
text=text, language_code=language)
# html and summary fields are denormalized in .save() call
if question.wiki:
#DATED COMMENT
# TODO: this is confusing - last_edited_at field
# is used as an indicator whether question has been edited
# but in principle, post creation should count as edit as well
question.last_edited_by = question.author
question.last_edited_at = added_at
question.wikified_at = added_at
# save question to have id for revision
question.save()
revision = question.add_revision(
author=author,
is_anonymous=is_anonymous,
text=text,
comment=str(const.POST_STATUS['default_version']),
revised_at=added_at,
by_email=by_email,
email_address=email_address,
ip_addr=ip_addr
)
# this is kind of bad, but we save assign privacy groups to posts and thread
# this call is rather heavy, we should split into several functions
parse_results = question.parse_and_save(author=author, is_private=is_private)
# moderate inline html items (e.g. links, images)
question.moderate_html()
author_group = author.get_personal_group()
thread.add_to_groups([author_group], visibility=ThreadToGroup.SHOW_PUBLISHED_RESPONSES)
question.add_to_groups([author_group])
if is_private or group_id: # add groups to thread and question
thread.make_private(author, group_id=group_id)
else:
thread.make_public()
# INFO: Question has to be saved before update_tags() is called
thread.update_tags(tagnames=tagnames,
user=author,
timestamp=added_at,
suppress_signals=[signals.tags_updated])
# TODO: this is handled in signal because models for posts
# are too spread out
if revision.revision > 0:
signals.post_updated.send(
post=question, updated_by=author,
newly_mentioned_users=parse_results['newly_mentioned_users'],
timestamp=added_at, created=True, diff=parse_results['diff'],
sender=question.__class__)
return thread
def get_for_query(self, search_query, qs=None):
"""returns a query set of questions,
matching the full text query
TODO: move to query set
"""
if getattr(django_settings, 'ENABLE_HAYSTACK_SEARCH', False):
from askbot.search.haystack.helpers import get_threads_from_query
return get_threads_from_query(search_query)
else:
if not qs:
qs = self.all()
# if getattr(settings, 'USE_SPHINX_SEARCH', False):
# matching_questions = Question.sphinx_search.query(search_query)
# question_ids = [q.id for q in matching_questions]
# return qs.filter(posts__post_type='question', posts__deleted=False, posts__self_question_id__in=question_ids)
if askbot.get_database_engine_name().endswith('mysql') \
and mysql.supports_full_text_search():
return qs.filter(
models.Q(title__search=search_query) |
models.Q(tagnames__search=search_query) |
models.Q(posts__deleted=False, posts__text__search=search_query)
)
elif 'postgresql_psycopg2' in askbot.get_database_engine_name():
from askbot.search import postgresql
return postgresql.run_thread_search(qs, search_query)
else:
return qs.filter(
models.Q(title__icontains=search_query) |
models.Q(tagnames__icontains=search_query) |
models.Q(posts__deleted=False, posts__text__icontains=search_query)
)
# TODO: !! review, fix, and write tests for this
def run_advanced_search(self, request_user, search_state):
"""
all parameters are guaranteed to be clean
however may not relate to database - in that case
a relvant filter will be silently dropped
"""
from askbot.conf import settings as askbot_settings # Avoid circular import
primary_filter = {
'posts__post_type': 'question',
'posts__deleted': False
}
lang_mode = askbot.get_lang_mode()
if lang_mode == 'url-lang':
primary_filter['language_code'] = get_language()
elif lang_mode == 'user-lang':
if request_user.is_authenticated:
language_codes = request_user.get_languages()
else:
language_codes = list(dict(django_settings.LANGUAGES).keys())
primary_filter['language_code__in'] = language_codes
# TODO: add a possibility to see deleted questions
qs = self.filter(**primary_filter)
if askbot_settings.CONTENT_MODERATION_MODE == 'premoderation':
if request_user.is_authenticated:
qs = qs.filter(Q(approved=True) | Q(posts__author_id=request_user.pk))
else:
qs = qs.filter(approved=True)
# if groups feature is enabled, filter out threads
# that are private in groups to which current user does not belong
if askbot_settings.GROUPS_ENABLED:
# get group names
qs = qs.get_visible(user=request_user)
# run text search while excluding any modifier in the search string
# like # tag [title: something] @user
if search_state.stripped_query:
qs = self.get_for_query(search_query=search_state.stripped_query, qs=qs)
# we run other things after full text search, because
# FTS may break the chain of the query set calls,
# since it might go into an external asset, like Solr
# search in titles, if necessary
if search_state.query_title:
qs = qs.filter(title__icontains=search_state.query_title)
# search user names if @user is added to search string
# or if user name exists in the search state
if search_state.query_users:
query_users = User.objects.filter(username__in=search_state.query_users)
if query_users:
# TODO: unify with search_state.author ?
qs = qs.filter(posts__post_type='question',
posts__author__in=query_users)
# unified tags - is list of tags taken from the tag selection
# plus any tags added to the query string with #tag or [tag:something]
# syntax.
# run tag search in addition to these unified tags
meta_data = {}
tags = search_state.unified_tags()
if len(tags) > 0:
if askbot_settings.TAG_SEARCH_INPUT_ENABLED:
# TODO: this may be gone or disabled per option
# "tag_search_box_enabled"
existing_tags = set()
non_existing_tags = set()
# we're using a one-by-one tag retreival, b/c
# we want to take advantage of case-insensitive search indexes
# in postgresql, plus it is most likely that there will be
# only one or two search tags anyway
for tag in tags:
try:
tag_record = Tag.objects.get(
name__iexact=tag, language_code=get_language())
existing_tags.add(tag_record.name)
except Tag.DoesNotExist:
non_existing_tags.add(tag)
meta_data['non_existing_tags'] = list(non_existing_tags)
tags = existing_tags
else:
meta_data['non_existing_tags'] = list()
# AND across tags: fetch only threads tagged with every requested tag.
# The natural ORM expression — one .filter(tags__name=tag) per tag —
# produces a JOIN through the M2M for every tag, which scales
# superlinearly and degrades to multi-second response times for
# 6-8 tag queries even on small datasets. The subquery + HAVING
# COUNT form is the relational idiom for set intersection.
# Deduplicate: unified_tags() concatenates query_tags + tags,
# so the same tag can appear twice; an inflated len() would
# never match Count(distinct=True). Empty list means all
# requested tags were unknown, in which case the search is
# unfiltered by tags (the names are reported via meta_data).
tags = list(set(tags))
if tags:
ThreadTagModel = self.model.tags.through
matching_thread_ids = (
ThreadTagModel.objects
.filter(tag__name__in=tags)
.values('thread_id')
.annotate(matched=Count('tag_id', distinct=True))
.filter(matched=len(tags))
.values_list('thread_id', flat=True)
)
qs = qs.filter(id__in=matching_thread_ids)
else:
meta_data['non_existing_tags'] = list()
if search_state.scope == 'unanswered':
# Do not show closed questions in unanswered section
qs = qs.filter(closed=False)
if askbot_settings.UNANSWERED_QUESTION_MEANING == 'NO_ANSWERS':
# TODO: this will introduce a problem if there are private answers
# which are counted here
# TODO: expand for different meanings of this
qs = qs.filter(answer_count=0)
elif askbot_settings.UNANSWERED_QUESTION_MEANING == 'NO_ACCEPTED_ANSWERS':
qs = qs.filter(accepted_answer__isnull=True)
elif askbot_settings.UNANSWERED_QUESTION_MEANING == 'NO_UPVOTED_ANSWERS':
raise NotImplementedError()
else:
raise Exception('UNANSWERED_QUESTION_MEANING setting is wrong')
elif search_state.scope == 'followed':
followed_filter = models.Q(favorited_by=request_user)
if 'followit' in django_settings.INSTALLED_APPS:
followed_users = request_user.get_followed_users()
followed_filter |= models.Q(posts__post_type__in=('question', 'answer'), posts__author__in=followed_users)
# a special case: "personalized" main page only ==
# if followed is the only available scope
# if total number (regardless of users selections)
# followed questions is < than a pagefull - we should mix in a list of
# random questions
if askbot_settings.ALL_SCOPE_ENABLED == askbot_settings.UNANSWERED_SCOPE_ENABLED == False:
followed_question_count = qs.filter(followed_filter).distinct().count()
if followed_question_count < 30:
# here we mix in anything
followed_filter |= models.Q(deleted=False)
qs = qs.filter(followed_filter)
# user contributed questions & answers
if search_state.author:
try:
# TODO: maybe support selection by multiple authors
u = User.objects.get(id=int(search_state.author))
except User.DoesNotExist:
meta_data['author_name'] = None
else:
qs = qs.filter(posts__post_type='question', posts__author=u,
posts__deleted=False)
meta_data['author_name'] = u.username
# get users tag filters
if request_user and request_user.is_authenticated:
# mark questions tagged with interesting tags
# a kind of fancy annotation, would be nice to avoid it
lang = get_language()
interesting_tags = Tag.objects.filter(
user_selections__user=request_user,
user_selections__reason='good',
language_code=lang)
ignored_tags = Tag.objects.filter(
user_selections__user=request_user,
user_selections__reason='bad',
language_code=lang)
subscribed_tags = Tag.objects.none()
if askbot_settings.SUBSCRIBED_TAG_SELECTOR_ENABLED:
subscribed_tags = Tag.objects.filter(
user_selections__user=request_user,
user_selections__reason='subscribed',
language_code=lang)
meta_data['subscribed_tag_names'] = [tag.name for tag in subscribed_tags]
meta_data['interesting_tag_names'] = [tag.name for tag in interesting_tags]
meta_data['ignored_tag_names'] = [tag.name for tag in ignored_tags]
if request_user.display_tag_filter_strategy == const.INCLUDE_INTERESTING and (interesting_tags or request_user.has_interesting_wildcard_tags()):
# filter by interesting tags only
interesting_tag_filter = models.Q(tags__in=interesting_tags)
if request_user.has_interesting_wildcard_tags():
interesting_wildcards = request_user.interesting_tags.split()
extra_interesting_tags = Tag.objects.get_by_wildcards(interesting_wildcards)
interesting_tag_filter |= models.Q(tags__in=extra_interesting_tags)
qs = qs.filter(interesting_tag_filter)
# get the list of interesting and ignored tags (interesting_tag_names, ignored_tag_names) = (None, None)
if request_user.display_tag_filter_strategy == const.EXCLUDE_IGNORED and (ignored_tags or request_user.has_ignored_wildcard_tags()):
# exclude ignored tags if the user wants to
qs = qs.exclude(tags__in=ignored_tags)
if request_user.has_ignored_wildcard_tags():
ignored_wildcards = request_user.ignored_tags.split()
extra_ignored_tags = Tag.objects.get_by_wildcards(ignored_wildcards)
qs = qs.exclude(tags__in=extra_ignored_tags)
if request_user.display_tag_filter_strategy == const.INCLUDE_SUBSCRIBED \
and subscribed_tags:
qs = qs.filter(tags__in=subscribed_tags)
if askbot_settings.USE_WILDCARD_TAGS:
meta_data['interesting_tag_names'].extend(request_user.interesting_tags.split())
meta_data['ignored_tag_names'].extend(request_user.ignored_tags.split())
QUESTION_ORDER_BY_MAP = {
'age-desc': '-added_at',
'age-asc': 'added_at',
'activity-desc': '-last_activity_at',
'activity-asc': 'last_activity_at',
'answers-desc': '-answer_count',
'answers-asc': 'answer_count',
'votes-desc': '-points',
'votes-asc': 'points',
'relevance-desc': '-relevance', # special Postgresql-specific ordering, 'relevance' quaso-column is added by get_for_query()
}
orderby = QUESTION_ORDER_BY_MAP[search_state.sort]
if not (getattr(django_settings, 'ENABLE_HAYSTACK_SEARCH', False) \
and orderby == '-relevance'):
# FIXME: this does not produces the very same results as postgres.
qs = qs.extra(order_by=[orderby])
# HACK: We add 'ordering_key' column as an alias and order by it, because when distict() is used,
# qs.extra(order_by=[orderby,]) is lost if only `orderby` column is from askbot_post!
# Removing distinct() from the queryset fixes the problem, but we have to use it here.
# UPDATE: Apparently we don't need distinct, the query don't duplicate Thread rows!
# qs = qs.extra(select={'ordering_key': orderby.lstrip('-')}, order_by=['-ordering_key' if orderby.startswith('-') else 'ordering_key'])
# qs = qs.distinct()
qs = qs.only(
'id', 'title', 'view_count', 'answer_count', 'last_activity_at',
'last_activity_by', 'closed', 'tagnames', 'accepted_answer'
)
return qs.distinct(), meta_data
def precache_view_data_hack(self, threads):
# TODO: Re-enable this when we have a good test cases to verify that it works properly.
#
# E.g.: - make sure that not precaching give threads never increase # of db queries for the main page
# - make sure that it really works, i.e. stuff for non-cached threads is fetched properly
# Precache data only for non-cached threads - only those will be rendered
# threads = [thread for thread in threads if not thread.summary_html_cached()]
thread_ids = [obj.id for obj in threads]
from askbot.models.post import Post
page_questions = Post.objects\
.filter(post_type='question', thread__id__in=thread_ids)\
.only('id', 'thread', 'points', 'is_anonymous',
'summary', 'post_type', 'deleted')
page_question_map = {}
for pq in page_questions:
page_question_map[pq.thread_id] = pq
for thread in threads:
thread._question_cache = page_question_map[thread.id]
last_activity_by_users = User.objects\
.filter(id__in=[obj.last_activity_by_id for obj in threads])\
.only('id', 'username', 'askbot_profile__country',
'askbot_profile__show_country')
user_map = {}
for la_user in last_activity_by_users:
user_map[la_user.id] = la_user
for thread in threads:
thread._last_activity_by_cache = user_map[thread.last_activity_by_id]
# TODO: this function is similar to get_response_receivers - profile this function against the other one
def get_thread_contributors(self, thread_list):
"""Returns query set of Thread contributors"""
# INFO: Evaluate this query to avoid subquery in the subsequent query below (At least MySQL can be awfully slow on subqueries)
from askbot.models.post import Post
u_id = list(
Post.objects
.filter(post_type__in=('question', 'answer'),
thread__in=thread_list)
.values_list('author', flat=True)
.distinct()
)
# TODO: this does not belong gere - here we select users with real faces
# first and limit the number of users in the result for display
# on the main page, we might also want to completely hide fake gravatars
# and show only real images and the visitors - even if he does not have
# a real image and try to prompt him/her to upload a picture
from askbot.conf import settings as askbot_settings
avatar_limit = askbot_settings.SIDEBAR_MAIN_AVATAR_LIMIT
contributors = User.objects\
.filter(id__in=u_id)\
.order_by('askbot_profile__avatar_type')[:avatar_limit]
return contributors
def get_for_user(self, user):
"""returns threads where a given user had participated"""
from askbot.models.post import PostRevision
from askbot.models.post import Post
post_ids = PostRevision.objects \
.filter(author=user) \
.values_list('post_id', flat=True) \
.distinct()
thread_ids = Post.objects \
.filter(id__in=post_ids) \
.values_list('thread_id', flat=True) \
.distinct()
return self.filter(id__in=thread_ids)
class ThreadToGroup(models.Model):
"""the "through" many-to-many relation between
threads and groups - to distinguish full and "what's published"
visibility of threads to various groups
"""
SHOW_PUBLISHED_RESPONSES = 0
SHOW_ALL_RESPONSES = 1
VISIBILITY_CHOICES = (
(SHOW_PUBLISHED_RESPONSES, 'show only published responses'),
(SHOW_ALL_RESPONSES, 'show all responses')
)
thread = models.ForeignKey('Thread', on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
visibility = models.SmallIntegerField(choices=VISIBILITY_CHOICES,
default=SHOW_ALL_RESPONSES)
class Meta:
unique_together = ('thread', 'group')
db_table = 'askbot_thread_groups'
app_label = 'askbot'
verbose_name = _("thread to group")
verbose_name_plural = _("threads to groups")
class Thread(models.Model):
title = models.CharField(max_length=300)
tags = models.ManyToManyField('Tag', related_name='threads')
groups = models.ManyToManyField(Group, through=ThreadToGroup,
related_name='group_threads')
# Denormalised data, transplanted from Question
tagnames = models.CharField(max_length=125)
view_count = models.PositiveIntegerField(default=0)
favourite_count = models.PositiveIntegerField(default=0)
answer_count = models.PositiveIntegerField(default=0)
last_activity_at = models.DateTimeField(default=timezone.now)
last_activity_by = models.ForeignKey(User, related_name='unused_last_active_in_threads', on_delete=models.CASCADE)
language_code = LanguageCodeField()
# TODO: these two are redundant (we used to have a "star" and "subscribe"
# now merged into "followed")
followed_by = models.ManyToManyField(User, related_name='followed_threads')
favorited_by = models.ManyToManyField(User, through='FavoriteQuestion',
related_name='unused_favorite_threads')
closed = models.BooleanField(default=False)
closed_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) # , related_name='closed_questions')
closed_at = models.DateTimeField(null=True, blank=True)
close_reason = models.SmallIntegerField(choices=const.CLOSE_REASONS,
null=True,
blank=True)
close_reason_text = models.CharField(max_length=256, default='', blank=True)
deleted = models.BooleanField(default=False, db_index=True)
# denormalized data: the core approval of the posts is made
# in the revisions. In the revisions there is more data about
# approvals - by whom and when
approved = models.BooleanField(default=True, db_index=True)
accepted_answer = models.ForeignKey('Post', null=True, blank=True, related_name='+', on_delete=models.CASCADE)
added_at = models.DateTimeField(auto_now_add=True)
# db_column will be removed later
points = models.IntegerField(default=0, db_column='score')
objects = ThreadManager()
class Meta:
app_label = 'askbot'
# property to support legacy themes in case there are.
@property
def score(self):
return int(self.points)
@score.setter
def score(self, number):
if number:
self.points = int(number)
def _question_post(self, refresh=False):
if refresh and hasattr(self, '_question_cache'):
delattr(self, '_question_cache')
post = getattr(self, '_question_cache', None)
if post:
return post
from askbot.models.post import Post
self._question_cache = Post.objects.get(post_type='question', thread=self)
return self._question_cache
def apply_hinted_tags(self, hints=None, user=None, timestamp=None, silent=False):
"""match words in title and body with hints
and apply some of the hints as tags,
so that total number of tags in no more
than the maximum allowed number of tags"""
# 1) see how many tags we're missing,
# if we don't need more we return
existing_tags = self.get_tag_names()
tags_count = len(existing_tags)
if tags_count >= askbot_settings.MAX_TAGS_PER_POST:
return
# 2) get set of words from title and body
post_text = self.title + ' ' + self._question_post().text
post_text = post_text.lower() # normalize
post_words = set(post_text.split())
# 3) get intersection set
# normalize hints and tags and remember the originals
orig_hints = dict()
for hint in hints:
orig_hints[hint.lower()] = hint
norm_hints = list(orig_hints.keys())
norm_tags = [v.lower() for v in existing_tags]
common_words = (set(norm_hints) & post_words) - set(norm_tags)
# 4) for each common word count occurances in corpus
counts = dict()
for word in common_words:
counts[word] = sum([w.lower() == word.lower() for w in post_words])
# 5) sort words by count
sorted_words = sorted(
common_words,
key=lambda a: counts[a],
reverse=True)
# 6) extract correct number of most frequently used tags
need_tags = askbot_settings.MAX_TAGS_PER_POST - len(existing_tags)
add_tags = sorted_words[0:need_tags]
add_tags = [orig_hints[h] for h in add_tags]
tagnames = ' '.join(existing_tags + add_tags)
if askbot_settings.FORCE_LOWERCASE_TAGS:
tagnames = tagnames.lower()
self.retag(
retagged_by=user,
retagged_at=timestamp or timezone.now(),
tagnames=' '.join(existing_tags + add_tags),
silent=silent
)
def get_absolute_url(self):
return self._question_post().get_absolute_url(thread=self)
# question_id = self._question_post().id
# return reverse('question', args = [question_id]) + slugify(self.title)
def get_answer_count(self, user=None):
"""returns answer count depending on who the user is.
When user groups are enabled and some answers are hidden,
the answer count to show must be reflected accordingly"""
if askbot_settings.GROUPS_ENABLED:
return self.get_answers(user).count()
return self.answer_count
def get_oldest_answer_id(self, user=None):
"""give oldest visible answer id for the user"""
answers = self.get_answers(user=user).order_by('added_at')
if len(answers) > 0:
return answers[0].id
return None
def get_answer_ids(self, user=None):
"""give the ids to all the answers for the user"""
answers = self.get_answers(user=user)
return [answer.id for answer in answers]
def get_flag_counts_by_post_id(self, user):
"""Returns a dictionary post_id -> flag_count"""
if user.is_anonymous:
return {}
from askbot.models import Post
post_ids = Post.objects.filter(thread_id=self.pk).only('pk')
flags = Activity.objects.filter(object_id__in=post_ids,
content_type=ContentType.objects.get_for_model(Post),
user_id=user.pk,
activity_type=const.TYPE_ACTIVITY_MARK_OFFENSIVE)
flags = flags.only('pk', 'object_id')
result = collections.defaultdict(int)
for flag in flags:
result[flag.object_id] += 1
return dict(result)
def get_latest_revision(self, user=None):
# TODO: add denormalized field to Thread model
from askbot.models import Post, PostRevision
posts_filter = {
'thread': self,
'post_type__in': ('question', 'answer'),
'deleted': False
}
if user and user.is_authenticated and askbot_settings.GROUPS_ENABLED:
# get post with groups shared with having at least
# one of the user groups
# of those posts return the latest revision
posts_filter['groups__in'] = user.get_groups()
posts = Post.objects.filter(**posts_filter)
post_ids = list(posts.values_list('id', flat=True))
revs = PostRevision.objects.filter(post__id__in=post_ids,
revision__gt=0)
try:
return revs.order_by('-id')[0]
except IndexError:
return None
def get_sharing_info(self, visitor=None):
"""returns a dictionary with abbreviated thread sharing info:
* users - up to a certain number of users, excluding the visitor
* groups - up to a certain number of groups
* more_users_count - remaining count of shared-with users
* more_groups_count - remaining count of shared-with groups
"""
# "visitor" is implicit
shared_users = self.get_users_shared_with(max_count=2,
exclude_user=visitor)
groups = self.groups
ugroups = groups.get_personal()
ggroups = groups.exclude_personal()
sharing_info = {
'users': shared_users,
'groups': self.get_groups_shared_with(max_count=3),
'more_users_count': max(0, ugroups.count() - 3),
'more_groups_count': max(0, ggroups.count() - 3)
}
return sharing_info
def get_users_shared_with(self, max_count=None, exclude_user=None):
"""returns query set of users with whom
this thread is shared
"""
filter = (
models.Q(thread=self, visibility=ThreadToGroup.SHOW_ALL_RESPONSES) &
models.Q(group__name__startswith=PERSONAL_GROUP_NAME_PREFIX))
if exclude_user:
user_group = exclude_user.get_personal_group()
filter = filter & ~models.Q(group_id=user_group.id)
thread_groups = ThreadToGroup.objects.filter(filter)
if max_count:
thread_groups = thread_groups[:max_count]
group_ids = thread_groups.values_list('group_id', flat=True)
group_ids = list(group_ids) # force query for MySQL
from askbot.models import GroupMembership
user_ids = GroupMembership.objects.filter(group__id__in=group_ids)\
.values_list('user__id', flat=True)
return User.objects.filter(id__in=user_ids)
def get_groups_shared_with(self, max_count=None):
"""returns query set of groups with whom thread is shared"""
thread_groups = ThreadToGroup.objects.filter(
models.Q(thread=self, visibility=ThreadToGroup.SHOW_ALL_RESPONSES) &~
models.Q(group__name__startswith=PERSONAL_GROUP_NAME_PREFIX))
if max_count:
thread_groups = thread_groups[:max_count]
group_ids = thread_groups.values_list('group_id', flat=True)
return Group.objects.filter(id__in=list(group_ids)) # force list 4 mysql
def update_favorite_count(self):
self.favourite_count = FavoriteQuestion.objects.filter(thread=self).count()
self.save()
def update_answer_count(self):
self.answer_count = self.get_answers().count()
self.save()
def increase_view_count(self, increment=1):
qset = Thread.objects.filter(id=self.id)
qset.update(view_count=models.F('view_count') + increment)
# get the new view_count back because other pieces of code relies on such behaviour
self.view_count = qset.values('view_count')[0]['view_count']
####################################################################
self.invalidate_cached_summary_html()
if not getattr(django_settings, 'CELERY_TASK_ALWAYS_EAGER', False):
self.update_summary_html() # proactively regenerate thread summary html
####################################################################
def set_closed_status(self, closed, closed_by, closed_at, close_reason_text):
self.closed = closed
self.closed_by = closed_by
self.closed_at = closed_at
self.close_reason_text = close_reason_text
self.save()
self.reset_cached_data()
def set_tags_language_code(self, language_code=None):
"""sets language code to tags of this thread.
If lang code of the tag does not coincide with that
of thread, we replace the tag with the one of correct
lang code. If necessary, tags are created and
the used_counts are updated.
"""
wrong_lang_tags = list()
for tag in self.tags.all():
if tag.language_code != language_code:
wrong_lang_tags.append(tag)
# remove wrong tags
self.tags.remove(*wrong_lang_tags)
# update used counts of the wrong tags
wrong_lang_tag_names = list()
for tag in wrong_lang_tags:
wrong_lang_tag_names.append(tag.name)
if tag.used_count > 0:
tag.decrement_used_count()
tag.save()
# load existing tags and figure out which tags don't exist
reused_tags, new_tagnames = get_tags_by_names(
wrong_lang_tag_names, language_code=language_code)
reused_tags.mark_undeleted()
# tag moderation is in the call below
created_tags = Tag.objects.create_in_bulk(
language_code=self.language_code, tag_names=new_tagnames,
user=self.last_activity_by, auto_approve=True)
# add the tags
added_tags = list(reused_tags) + list(created_tags)
self.tags.add(*added_tags)
# increment the used counts and save tags
tag_ids = [tag.id for tag in added_tags]
Tag.objects.filter(id__in=tag_ids).update(used_count=F('used_count')+1)
def set_language_code(self, language_code=None):
assert(language_code)
# save language code on thread
self.language_code = language_code
self.save()
# save language code on all posts
# for some reason "update" fails in postgres - possibly b/c of the FTS
for post in self.posts.all():
post.language_code = language_code
post.save()
# update language of the reputes on the question
question = self._question_post()
from askbot.models import Repute
reputes = Repute.objects.filter(question=question)
reputes.update(language_code=language_code)
# make sure that tags have correct language code
self.set_tags_language_code(language_code)
def set_accepted_answer(self, answer, actor, timestamp):
if answer and answer.thread != self:
raise ValueError("Answer doesn't belong to this thread")
# TODO: in the future there may be >1 accepted answer
self.accepted_answer = answer
self.set_last_activity_info(timestamp, actor)
self.save()
answer.endorsed = True
answer.endorsed_at = timestamp
answer.endorsed_by = actor
answer.save()
def set_last_activity_info(self, last_activity_at, last_activity_by):
self.last_activity_at = last_activity_at
self.last_activity_by = last_activity_by
def get_last_activity_info(self):
post_ids = self.get_answers().values_list('id', flat=True)
question = self._question_post()
post_ids = list(post_ids)
post_ids.append(question.id)
from askbot.models import PostRevision
revs = PostRevision.objects.filter(post__id__in=post_ids,
revision__gt=0).order_by('-id')
try:
rev = revs[0]
return rev.revised_at, rev.author
except IndexError:
return None, None
def update_last_activity_info(self):
timestamp, user = self.get_last_activity_info()
if timestamp:
self.set_last_activity_info(timestamp, user)
self.save()
def get_tag_names(self):
"Creates a list of Tag names from the ``tagnames`` attribute."
if self.tagnames.strip() == '':
return list()
else:
return self.tagnames.split(' ')
def get_title(self):
title_renderer = load_plugin(
'ASKBOT_QUESTION_TITLE_RENDERER',
'askbot.models.question.default_title_renderer')
return title_renderer(self)
def get_answers_by_user(self, user):
"""regardless - deleted or not"""
return self.posts.filter(post_type='answer', author=user,
deleted=False)