def setUserSelection(request):
    response = {}
    try:
        selection = getUserSelection(request)
        tableId = request.GET['tableId']
        if ('selected' in request.GET and request.GET['selected'] == '_all') or \
            ('unselected' in request.GET and request.GET['unselected'] == '_all'):
            selectUselectAll(request)
        else:
            if 'selected' in request.GET:
                queryset = getItemQueryset(request.GET['selected'])
                selection.selectRow(tableId, queryset)
            elif 'unselected' in request.GET:
                queryset = getItemQueryset(request.GET['unselected'])
                selection.unselectRow(tableId, queryset)
            else:
                raise Exception('"selected" or "unselected" parameter must be present')

        options = [(name[4:], request.GET[name]) for name in request.GET.keys() if 'opt_' in name]
        for option in options:
            selection.setQueryOption(tableId, option[0], option[1])
        response['selectedCount'] = selection.getSelectedRowCount()
        response['status'] = 'completed'
    except:
        viewsLogger.exception("AN ERROR OCCURED IN setUserSelection")
        response = {'status': 'error', 'error': {'description': 'An error occured in views'}}
    return HttpResponse(json.dumps(response), content_type='application/json')
Пример #2
0
def setUserSelection(request):
    response = {}
    try:
        selection = getUserSelection(request)
        tableId = request.GET['tableId']
        if ('selected' in request.GET and request.GET['selected'] == '_all') or \
                ('unselected' in request.GET and request.GET['unselected'] == '_all'):
            selectUnselectAll(request)
        else:
            if 'selected' in request.GET:
                queryset = getItemQueryset(request.GET['selected'])
                selection.selectRow(tableId, queryset)
            elif 'unselected' in request.GET:
                queryset = getItemQueryset(request.GET['unselected'])
                selection.unselectRow(tableId, queryset)

        options = [(name[4:], request.GET[name]) for name in request.GET.keys() if 'opt_' in name]
        for option in options:
            selection.setQueryOption(tableId, option[0], option[1])
        response['selectedCount'] = selection.getSelectedRowCount()
        response['status'] = 'completed'
    except:
        viewsLogger.exception("AN ERROR OCCURED IN setUserSelection")
        response = {'status': 'error', 'error': {'description': 'An error occured in views'}}
    return HttpResponse(json.dumps(response), content_type='application/json')
def ajax_pieChart(request):
    reqId = None
    if 'tqx' in request.GET:
        reqId = request.GET['tqx'].split(':')[1]
    try:
        response = {
            "status": 'ok',
            'reqId': reqId,
            "table": generatepieChartTable(request),
        }
    except Exception as e:
        viewsLogger.exception('An error has occured while creating a PieChart')
        response = {
            'status': 'error',
            'reqId': reqId,
            'errors':[
                {
                    'reason':'internal_error',
                    'message': 'An error has occured while generating the data',
                    'detailed_message': str(e),
                }
            ],

        }
    return HttpResponse("google.visualization.Query.setResponse(%s)" % json.dumps(response),
                        content_type='application/json')
def formBase(request, formName):
    if not request.user.is_authenticated(): return jsonUnauthorizedError(request)
    if not formName in validFormNames: return jsonBadRequest(request, 'Specified form does not exists')
    try:
        return globals()[formName](request)
    except:
        viewsLogger.exception("ERROR OCCURED IN %s AJAX WITH FORM NAME '%s':" % (__name__,formName))
        return jsonUnknownError(request)
def ajaxBase(request):
    if not request.user.is_authenticated(): return jsonUnauthorizedError(request)
    if not 'tableId' in request.GET: return jsonBadRequest(request, 'tableId not defined')
    tableId = request.GET['tableId']
    if not tableId in validTableIds: return jsonBadRequest(request, 'Wrong tableId defined')
    try:
        return globals()[tableId](request)
    except:
        viewsLogger.exception("ERROR OCCURED IN YOUTUBE AJAX WITH TABLEID=%s"% tableId)
        return jsonUnknownError(request)
def ajaxTWUserMentions(request, TWUserId):
    try:
        twUser = get_object_or_404(TWUser, pk=TWUserId)
        queryset = twUser.mentions.filter(retweet_of__isnull=True)
        tableRowsSelections = getUserSelection(request)
        selecteds = tableRowsSelections.getSavedQueryset("Tweet", 'TWUserMentionsTable')
        return ajaxResponse(queryset, request, selecteds)
    except:
        viewsLogger.exception("Error occured in ajaxTWUserMentions:")
        return error500json(request)
def ajaxTWFollowersTable(request, TWUserId):
    try:
        twUser = get_object_or_404(TWUser, pk=TWUserId)
        queryset = twUser.followers.all()
        tableRowsSelections = getUserSelection(request)
        selecteds = tableRowsSelections.getSavedQueryset("follower", 'TWFollowersTable')
        return ajaxResponse(queryset, request, selecteds)
    except:
        viewsLogger.exception("Error occured in ajaxTWUserMentions:")
        return error500json(request)
def TWRepliesTable(request, TweetId):
    try:
        tweet = get_object_or_404(Tweet, pk=TweetId)
        queryset = tweet.replied_by.all()
        tableRowsSelections = getUserSelection(request)
        selecteds = tableRowsSelections.getSavedQueryset("Tweet", 'TWTweetRepliesTable')
        return ajaxResponse(queryset, request, selecteds)
    except:
        viewsLogger.exception("Error occured in TWMentionnedUsers:")
        return error500json(request)
def TWContainedHashtags(request, TweetId):
    try:
        tweet = get_object_or_404(Tweet, pk=TweetId)
        queryset = tweet.hashtags.all()
        tableRowsSelections = getUserSelection(request)
        selecteds = tableRowsSelections.getSavedQueryset("Hashtag", 'TWContainedHashtagsTable')
        return ajaxResponse(queryset, request, selecteds)
    except:
        viewsLogger.exception("Error occured in TWMentionnedUsers:")
        return error500json(request)
def ajaxTWUserTweetTable(request, TWUserId):
    try:
        twUser = get_object_or_404(TWUser, pk=TWUserId)
        queryset = twUser.tweets.all()
        tableRowsSelections = getUserSelection(request)
        selecteds = tableRowsSelections.getSavedQueryset("Tweet", 'TWUserTweetTable')
        options = tableRowsSelections.getQueryOptions('TWUserTweetTable')
        if 'exclude_retweets' in options and options['exclude_retweets']:
            queryset = queryset.filter(retweet_of__isnull=True)
        return ajaxResponse(queryset, request, selecteds)
    except:
        viewsLogger.exception("Error occured in ajaxTWUserMentions:")
        return error500json(request)
def ajax_lineChart(request):
    reqId = None
    if 'tqx' in request.GET:
        reqId = request.GET['tqx'].split(':')[1]
    try:
        response = {
            "status": 'ok',
            'reqId':reqId,
            "table": generateLineChartTable(request),
        }
    except Exception as e:
        viewsLogger.exception('An error occured while creating a Linechart')
        response = {
            'status':'error',
            'message':e.args[0],
            'reqId':reqId,
        }
    return HttpResponse("google.visualization.Query.setResponse(%s)"%json.dumps(response),
                        content_type='application/json')
def ajaxTWTweetTable(request):
    try:
        #queryset = Tweet.objects.none()
        userSelection = getUserSelection(request)
        selectedTWUsers = userSelection.getSavedQueryset('TWUser', 'TWUserTable')
        selectedHashHarvesters = userSelection.getSavedQueryset('HashtagHarvester', 'TWHashtagTable')
        queryset = userSelection.getSavedQueryset('Tweet', 'TWTweetTable')
        options = userSelection.getQueryOptions('TWTweetTable')
        for user in selectedTWUsers.all():
            queryset = queryset | user.tweets.all()
        for hashtagHarvester in selectedHashHarvesters.all():
            queryset = queryset | hashtagHarvester.hashtag.tweets.all()
        if 'exclude_retweets' in options and options['exclude_retweets']:
            queryset = queryset.filter(retweet_of__isnull=True)
        selecteds = userSelection.getSavedQueryset("Tweet", 'TWTweetTable')
        return ajaxResponse(queryset.distinct(), request, selecteds)
    except:
        viewsLogger.exception("Error occured in ajaxTWTweetTable:")
        return error500json(request)
Пример #13
0
def ajax_lineChart(request):
    reqId = None
    if 'tqx' in request.GET:
        reqId = request.GET['tqx'].split(':')[1]
    try:
        response = {
            "status": 'ok',
            'reqId': reqId,
            "table": generateLineChartTable(request),
        }
    except Exception as e:
        viewsLogger.exception('An error occured while creating a Linechart')
        response = {
            'status': 'error',
            'message': e.args[0],
            'reqId': reqId,
        }
    return HttpResponse("google.visualization.Query.setResponse(%s)" %
                        json.dumps(response),
                        content_type='application/json')
Пример #14
0
from django.contrib.auth.decorators import login_required
from Twitter.models import *
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from SocialNetworkHarvester_v1p0.jsonResponses import *
from AspiraUser.models import getUserSelection, resetUserSelection
import re
from tool.views.ajaxTables import readLinesFromCSV
import tweepy

import re

from SocialNetworkHarvester_v1p0.settings import viewsLogger, DEBUG
log = lambda s: viewsLogger.log(s) if DEBUG else 0
pretty = lambda s: viewsLogger.pretty(s) if DEBUG else 0
logerror = lambda s: viewsLogger.exception(s) if DEBUG else 0


@login_required()
def addUser(request):
    occuredErrors = []
    userProfile = request.user.userProfile
    try:
        api = getTwitterApi(userProfile)
    except Exception as e:
        return HttpResponse(json.dumps({
            'status': 'exception',
            'errors': str(e)
        }),
                            content_type='application/json')
    screen_names = [
def userRegister(request):
    data = request.POST
    aspiraErrors = []
    masterAddrs = [user.email for user in User.objects.filter(is_superuser=True, email__isnull=False) if
                   user.email != '']
    log(masterAddrs)
    required_fields = {'username':'******',
                       'email': 'Email address',
                       'pw': 'Password'}
    context = {
        'user': request.user,
        'navigator': [
            ('Registration', '#')
        ]
    }

    for field in required_fields.keys():
        if field not in data or data[field] == '':
            aspiraErrors.append('%s is null, please insert a value'% required_fields[field])

    if not aspiraErrors and data['pw'] != data['pw_confirm']:
        aspiraErrors.append('The passwords dont match!')

    if not aspiraErrors and User.objects.filter(email=data['email']).exists():
        aspiraErrors.append('An account with that email already exists!')

    if not aspiraErrors and User.objects.filter(username=data['username']).exists():
        aspiraErrors.append('An account with this username already exists!')

    if not aspiraErrors:
        try:
            validate_email(data['email'])
        except ValidationError:
            aspiraErrors.append('The given email address doesn''t seem valid. Please verify it is correct.')

    if not aspiraErrors:
        message = render_to_string('AspiraUser/emails/newAccountInstructions.html', {
            'username': data['username'],
            'fname': data['fname'],
            'lname': data['lname'],
            'org': data['org'],
            'webmasters': masterAddrs,
        })
        send_mail('SNH - Account creation instructions', 'message',
              'doNotReplyMail', [data['email']], html_message=message)

    if not aspiraErrors:
        try:
            newUser = User.objects.create_user(data['username'],data['email'],data['pw'],
                first_name=data['fname'],
                last_name=data['lname'],
                is_active=False
            )
            newProfile = UserProfile.objects.create(user=newUser)
        except:
            viewsLogger.exception('An error occured while creating a new AspiraUser!')
            aspiraErrors.append('An error occured! Please contact the webmaster directly to create your account.')

    if not aspiraErrors:
        message = render_to_string('AspiraUser/emails/validateNewAccount.html', {
            'email':data['email'],
            'username':data['username'],
            'fname':data['fname'],
            'lname':data['lname'],
            'org':data['org'],
            'usageText':data['usageText'],
            'adminAuth': "https://%s/adminauth/user/%s/change/"%(request.get_host(), newUser.pk)
        })

        try:
            send_mail('SNH - New account creation request', 'message',
                  'doNotReplyMail', masterAddrs, html_message=message)
        except:
            viewsLogger.exception('An error occured while sending an email to %s'% masterAddrs)

    if aspiraErrors:
        request.session['aspiraErrors'] = aspiraErrors
        fieldKeeper = {}
        for field in ['fname', 'username', 'org', 'email', 'lname', 'usageText']:
            if field in data:
                fieldKeeper[field] = data[field]
        context['fieldKeeper'] = fieldKeeper
        template = 'AspiraUser/login_page.html'
    else:
        request.session['aspiraMessages'] = ["Thank you! You will receive an email as soon as your account "+
                                             "is approved by the webmaster."]
        template = 'AspiraUser/register_successful.html'
    request, context = addMessagesToContext(request, context)
    return render(request, template, context)
Пример #16
0
def userRegister(request):
    data = request.POST
    aspiraErrors = []
    masterAddrs = [user.email for user in User.objects.filter(is_superuser=True, email__isnull=False) if
                   user.email != '']
    required_fields = {'username':'******',
                       'email': 'Email address',
                       'pw': 'Password'}
    context = {
        'user': request.user,
        'navigator': [
            ('Enregistrement', '#')
        ]
    }

    for field in required_fields.keys():
        if field not in data or data[field] == '':
            aspiraErrors.append('Le champ "%s" est vide! Veuillez y insérer une valeur.'% required_fields[field])

    if not aspiraErrors and data['pw'] != data['pw_confirm']:
        aspiraErrors.append('Les mots de passe ne coincident pas!')

    if not aspiraErrors and len(data['pw']) < 6:
        aspiraErrors.append('Votre mot de passe doit avoir au moins 6 caractères.')

    if not aspiraErrors and User.objects.filter(email=data['email']).exists():
        aspiraErrors.append('Un compte avec cette adresse email existe déjà!')

    if not aspiraErrors and User.objects.filter(username=data['username']).exists():
        aspiraErrors.append('Un compte avec ce nom d\'utilisateur existe déjà!')

    if not aspiraErrors and not validate_userName(data['username']):
        aspiraErrors.append('Le nom d\'utilisateur ne peut contenir que des caractères alphanumériques.')

    if not aspiraErrors:
        try:
            validate_email(data['email'])
        except ValidationError:
            aspiraErrors.append('L\'adresse email fournie ne semble pas valide. Veuillez vérifier qu\'il '
                                'ne s\'agit pas d\'une erreur.')

    if not aspiraErrors:
        message = render_to_string('AspiraUser/emails/newAccountInstructions.html', {
            'username': data['username'],
            'fname': data['fname'],
            'lname': data['lname'],
            'org': data['org'],
            'webmasters': masterAddrs,
        })
        send_mail('SNH - Account creation instructions', 'message',
              'doNotReplyMail', [data['email']], html_message=message)

    if not aspiraErrors:
        try:
            newUser = User.objects.create_user(data['username'],data['email'],data['pw'],
                first_name=data['fname'],
                last_name=data['lname'],
                is_active=False
            )
            newProfile = UserProfile.objects.create(user=newUser)
        except:
            viewsLogger.exception('An error occured while creating a new AspiraUser!')
            aspiraErrors.append('An error occured! Please contact the webmaster directly to create your account.')

    if not aspiraErrors:
        message = render_to_string('AspiraUser/emails/validateNewAccount.html', {
            'email':data['email'],
            'username':data['username'],
            'fname':data['fname'],
            'lname':data['lname'],
            'org':data['org'],
            'usageText':data['usageText'],
            'adminAuth': "https://%s/adminauth/user/%s/change/"%(request.get_host(), newUser.pk)
        })

        try:
            send_mail('SNH - New account creation request', 'message',
                  'doNotReplyMail', masterAddrs, html_message=message)
        except:
            viewsLogger.exception('An error occured while sending an email to %s'% masterAddrs)

    if aspiraErrors:
        request.session['aspiraErrors'] = aspiraErrors
        fieldKeeper = {}
        for field in ['fname', 'username', 'org', 'email', 'lname', 'usageText']:
            if field in data:
                fieldKeeper[field] = data[field]
        context['fieldKeeper'] = fieldKeeper
        template = 'AspiraUser/login_page.html'
    else:
        request.session['aspiraMessages'] = ["Merci! Vous reçevrez un courriel aussitôt que \
        votre compte est approuvé par le webmaster."]
        template = 'AspiraUser/register_successful.html'
    request, context = addMessagesToContext(request, context)
    return render(request, template, context)