Exemplo n.º 1
0
def connect(url, survey_id):
    #print("Please enter your username")
    username=getpass(prompt="[?] Please enter your username:"******"Please enter your password")
    password=getpass(prompt="[?] Please enter your password:"******"Could not connect. Check url, username and password.")
        sys.exit(1)        


    surveys = {int(s['sid']): s for s in api.survey.list_surveys()}
    if len(surveys)>0:
        logger.info("Connected to server.")
        if survey_id == -1:
            return surveys
        else:        
            if survey_id in surveys.keys():
                title = surveys[survey_id]['surveyls_title']
                active = "active" if surveys[survey_id]['active'] == 'Y' else "inactive"
                logger.info("Selected survey: {}. Survey status: {}".format(title, active))
                return api
            else:
                logger.error("Selected survey not found")
                sys.exit(1)
    else:
        logger.error("Could not find any surveys")
        sys.exit(1)
Exemplo n.º 2
0
    def setUpClass(cls):

        # Read config.ini file
        current_dir = os.path.dirname(os.path.realpath(__file__))
        config_path = os.path.join(current_dir, 'config.ini')
        confparser = ConfigParser()
        with open(config_path, "r") as config_file:
            confparser.read_file(config_file)
        cls.url = confparser['test']['url']
        cls.username = confparser['test']['username']
        cls.password = confparser['test']['password']
        cls.api = LimeSurvey(url=cls.url, username=cls.username)
        cls.session_key = None
        cls.api.open(password=cls.password)

        surveys = sorted(cls.api.survey.list_surveys(), key=itemgetter("sid"))
        cls.survey_id = surveys[0].get("sid")
        cls.survey_id_invalid = -1
Exemplo n.º 3
0
    def perform_create(self, serializer):
        api_consulting = serializer.validated_data['api_consulting']
        email = serializer.validated_data['email']
        name = serializer.validated_data['name']

        token = ''
        if api_consulting == "YoffeCastanedaGattioniConsultores":
            url = settings.URL_API_LIME
            username = settings.USERNAME_API_LIME
            password = settings.PASSWD_API_LIME
            id_demo = settings.ID_DEMO_LIME

            # Open a session.
            api = LimeSurvey(url=url, username=username)
            api.open(password=password)
            respuesta = api.token.add_participants(id_demo, [{"email": email, "firstname": name}])
            try:
                dicc_respuesta = respuesta[0]
                token = dicc_respuesta['token']
            except IndexError:
                pass
            api.close()

        serializer.save(token=token)
Exemplo n.º 4
0
from limesurveyrc2api.limesurvey import LimeSurvey
import json
import logging
import argparse
import uuid

import emission.net.ext_service.push.notify_usage as pnu
import emission.net.ext_service.push.query.dispatch as pqd
import emission.core.wrapper.user as ecwu
import emission.net.ext_service.limesurvey.limesurvey as LimeSurvey

essai = LimeSurvey.get_instance()

essai.open_api()
print(essai.get_surveys_user(ecwu.User.fromEmail("*****@*****.**").uuid))
essai.close_api()
Exemplo n.º 5
0
 def __init__(self, url, username, password):
     self.api = LimeSurvey(url, username)
     self.api.open(password)
     self.logger = logging.getLogger(__name__)
Exemplo n.º 6
0
class LimeSurveySession(object):
    def __init__(self, url, username, password):
        self.api = LimeSurvey(url, username)
        self.api.open(password)
        self.logger = logging.getLogger(__name__)

    def __del__(self):
        self.api.close()

    def generate_new_survey_with_participants(self, template, name,
                                              participant_data):
        if name in self.get_existing_survey_names():
            raise IOError('Survey %s already exists!' % name)
        # import survey from given template
        survey_id = self.api.survey.import_survey(template, name)
        self.logger.info('Created new evaluation "%s"' % name)
        self.logger.info('Used template: %s' % template)
        self.logger.info('New survey id: %s' % survey_id)

        # activate tokens
        response = self.api.survey.activate_tokens(survey_id)
        if response['status'] == 'OK':
            self.logger.info('Initialised token system for survey %s' %
                             survey_id)
        else:
            self.logger.info(
                'Could not initialise token system for survey %s' % survey_id)
            self.logger.info('Message was: %s' % response)

        # add participants
        response = self.api.token.add_participants(survey_id, participant_data)
        for participant in response:  # detailed logging on added participants
            self.logger.info(
                'Added %s %s (email %s) to survey %s' %
                (participant['firstname'], participant['lastname'],
                 participant['email'], survey_id))
        self.logger.info('\n')
        return survey_id

    def list_all_surveys(self, term=None):
        all_surveys = self.api.survey.list_surveys()
        if term:  # filter surveys by term
            filtered_surveys = []
            for survey in all_surveys:
                if term in survey['surveyls_title']:
                    filtered_surveys.append(survey)
            return filtered_surveys
        else:
            return all_surveys

    def get_existing_survey_names(self, term=None):
        existing_surveys = self.api.survey.list_surveys()
        if term:
            return [
                survey['surveyls_title'] for survey in existing_surveys
                if term in survey['surveyls_title']
            ]
        else:
            return [survey['surveyls_title'] for survey in existing_surveys]

    def invite_all_participants(self, term):
        surveys = self.list_all_surveys(term=term)
        for survey in surveys:

            # logging of general info
            self.logger.info(
                'Going to invite all participants for survey "%s" (id %s)' %
                (survey['surveyls_title'], survey['sid']))

            # activate survey
            self.api.survey.activate_survey(survey['sid'])
            self.logger.info('Activated survey %s' % survey['sid'])

            # invite participants for this survey
            response = self.api.token.invite_participants(
                survey_id=survey['sid'], token_ids=False)  # invite all

            # detailed logging on invited participants
            for key, value in response.items():
                if key != 'status':
                    participant_info = value
                    name = participant_info['name']
                    email = participant_info['email']
                    if participant_info['status'] == 'OK':
                        self.logger.info(
                            'Email invitation was send to %s (email %s)' %
                            (name, email))
                    else:
                        self.logger.info(
                            'Error sending invitation for %s (email %s)' %
                            (name, email))
                        self.logger.info('Message was: %s' %
                                         participant_info['status'])

            # finish logging
            self.logger.info('Status for survey %s: %s\n' %
                             (survey['sid'], response['status']))

    def remind_all_participants(self, term):
        surveys = self.list_all_surveys(term=term)
        for survey in surveys:

            # logging of general info
            self.logger.info(
                'Going to remind all participants for survey "%s" (id %s)' %
                (survey['surveyls_title'], survey['sid']))

            # invite participants for this survey
            response = self.api.token.remind_participants(
                survey_id=survey['sid'])

            # detailed logging on invited participants
            for key, value in response.items():
                if key != 'status':
                    participant_info = value
                    name = participant_info['name']
                    email = participant_info['email']
                    if participant_info['status'] == 'OK':
                        self.logger.info(
                            'Email reminder was send to %s (email %s)' %
                            (name, email))
                    else:
                        self.logger.info(
                            'Error sending reminder for %s (email %s)' %
                            (name, email))
                        self.logger.info('Message was: %s' %
                                         participant_info['status'])

            # finish logging
            self.logger.info('Status for survey %s: %s\n' %
                             (survey['sid'], response['status']))

    def export_statistics(self, term, csv_folder):
        surveys = self.list_all_surveys(term)
        for survey in surveys:
            self.logger.info('Export response statistics for %s' %
                             survey['surveyls_title'])
            try:
                response = self.api.survey.export_responses(
                    survey['sid'],
                    document_type='csv',
                    heading_type='full',
                    response_type='long')
            except LimeSurveyError as e:
                self.logger.error(e)
                continue
            # TODO: Somehow use Lecture.get_filename() here?
            filename = clean_string(survey['surveyls_title']).replace(' ', '_')
            filename = filename.replace('Evaluation', 'Ergebnisse')
            filename += '.csv'
            outfile = os.path.join(csv_folder, filename)
            with open(outfile, 'wb') as f:
                f.write(b64decode(response))
            self.logger.info('... saved to %s' % outfile)

    def get_group_and_question_structure(self, survey_id):
        question_groups = self.get_question_groups(survey_id)
        group_and_question_structure = []
        for group in question_groups:
            group_structure = dict()
            group_id = group['gid']
            group_question_structure = self.get_question_structure_by_group(
                survey_id, group_id)
            group_structure['group_name'] = group['group_name']
            group_structure['group_questions'] = group_question_structure
            group_and_question_structure.append(group_structure)
        return group_and_question_structure

    def get_question_groups(self,
                            survey_id,
                            fields=['group_name', 'group_order', 'gid'],
                            sort_by='group_order'):
        question_groups = self.api.survey.list_groups(survey_id)
        return filter_and_sort_dicts(question_groups, sort_by, fields)

    def get_question_structure_by_group(self, survey_id, group_id):
        all_questions = self.api.survey.list_questions(survey_id, group_id)
        parent_questions = [
            question for question in all_questions
            if (question['parent_qid'] == '0')
        ]
        parent_questions = sort_dicts(parent_questions, 'question_order')
        question_structures = []
        for parent_question in parent_questions:
            question_structure = dict()
            question_structure['parent_question'] = parent_question['question']
            question_structure['type'] = parent_question['type']
            # get questions belonging to this parent question
            parent_qid = parent_question['qid']
            questions = [
                question for question in all_questions
                if (question['parent_qid']) == parent_qid
            ]
            questions = sort_dicts(questions, sort_by='question_order')
            questions = [question['question'] for question in questions]
            question_structure['child_questions'] = questions
            question_structures.append(question_structure)
        return question_structures

    def print_survey_participation(self, survey_id):
        summary = self.api.token.get_summary(survey_id)
        completed = summary['completed_responses']
        tokens = summary['token_count']
        incomplete = summary['incomplete_responses']
        # print('Survey participation for %s' % survey_id)
        print('Completed Responses: %s/%s (%.2f Prozent), %s incomplete' %
              (completed, tokens, int(completed) / int(tokens) * 100,
               incomplete))

    def get_survey_participation(self, survey_id):
        summary = self.api.token.get_summary(survey_id)
        completed = int(summary['completed_responses'])
        tokens = int(summary['token_count'])
        incomplete = int(summary['incomplete_responses'])
        return completed, tokens, incomplete
Exemplo n.º 7
0
list_participants

"""


from limesurveyrc2api.limesurvey import LimeSurvey
from limesurveyrc2api.exceptions import LimeSurveyError
from limesurveyrc2api._survey import _Survey
from limesurveyrc2api._token import _Token

url = "https://qpidsv.intra.infocamere.it/index.php/admin/remotecontrol"
username = "******"
password = "******"

# Open a session.
api = LimeSurvey(url=url, username=username)
api.open(password=password)

# Get a list of surveys the admin can see, and print their IDs.
result = api.survey.list_surveys()
#for survey in result:
#    print(survey.get("sid"))

# get data from survey # 531223
id_survey = 531223
token = _Token(api)
#search for email
email_target = "*****@*****.**"
tid = ""
part_start = 0
part_limit = 999999
import base64
from limesurveyrc2api.limesurvey import LimeSurvey

url = "https://livinginsmarthomes.limequery.com/admin/remotecontrol"
username = ""
password = ""

surveyID = ""

# Open a session.
api = LimeSurvey(url=url, username=username)
api.open(password=password)

# Get a list of surveys the admin can see, and print their IDs.
result = api.survey.list_surveys()
#for survey in result:
#print(survey.get("sid"))

# check if any questions have been uploaded previously
# this will replace all previous uploads
result = api.list_groups(surveyID)
if ('status' not in result):
    print("deleting all groups")
    for group in result:
        api.delete_group(surveyID, group['gid'])
#
print("uploading data ...")
up_file = open("output/question-group.lsg", "r")
data = up_file.read()
encoded = base64.b64encode(data.encode())
Exemplo n.º 9
0
 def open_api(self):
     self.api = LimeSurvey(url=self.url, username=self.username)
     self.api.open(password=self.password)
Exemplo n.º 10
0
class Limesurvey(object):
    def __init__(self, limesurvey_config):
        self.url = limesurvey_config["url"]
        self.username = limesurvey_config["username"]
        self.password = limesurvey_config["password"]
        self.url_surveys = limesurvey_config["url_surveys"]

    def open_api(self):
        self.api = LimeSurvey(url=self.url, username=self.username)
        self.api.open(password=self.password)

    def close_api(self):
        session_key_released = self.api.close()

    def get_all_surveys(self):
        result = self.api.survey.list_surveys()
        return result

    def add_participants_by_mail(self, survey_id, email_list):
        participant_list = []

        for email in email_list:
            # Retrieve uuid and convert it in hex to use it as a LimeSurvey invitation token
            token = ecwu.User.fromEmail(email).uuid.hex
            participant_list.append({
                "email":
                email,
                "token":
                token,
                "validfrom":
                time.strftime("%Y-%m-%d %H:%M", time.gmtime())
            })

        # create_token_key = False to disable the automatic generation
        response = self.api.token.add_participants(
            survey_id=survey_id,
            participant_data=participant_list,
            create_token_key=False)
        if "status" in response:
            if response["status"] == "No survey participants table":
                logging.warning(
                    "The survey %d as not been configured correctly, please read the doc for more informations"
                    % survey_id)

        return response

    def add_participants_by_uuid(self, survey_id, uuid_list):
        participant_list = []

        for uuid in uuid_list:
            token = uuid.hex
            email = ecwu.User.fromUUID(uuid)._User__email
            participant_list.append({
                "email":
                email,
                "token":
                token,
                "validfrom":
                time.strftime("%Y-%m-%d %H:%M", time.gmtime())
            })

        response = self.api.token.add_participants(
            survey_id=survey_id,
            participant_data=participant_list,
            create_token_key=False)
        if "status" in response:
            if response["status"] == "No survey participants table":
                logging.warning(
                    "The survey %d as not been configured correctly, please read the doc for more informations"
                    % survey_id)

        return response

    def get_participants_not_answered(self, survey_id):
        try:
            participant_list = self.api.token.list_participants(
                survey_id=survey_id, conditions={"completed": False})
            email_list = []
            for participant in participant_list:
                participant_info = participant["participant_info"]
                email_list.append(participant_info["email"])
            return email_list
        except:
            response = self.api.token.get_summary(survey_id=survey_id)
            if response["token_count"] == response["token_completed"]:
                logging.warning("Every participants has answered to %s" %
                                survey_id)
            else:
                logging.warning("No participants found in %s" % survey_id)
            return []

    def get_surveys_user(self, uuid):
        uuid = uuid.hex
        logging.debug("User token is %s" % uuid)
        surveys = self.get_all_surveys()
        user_surveys = []
        survey_count = 0

        for survey in surveys:
            try:
                result = self.api.token.list_participants(
                    survey_id=survey["sid"],
                    attributes=["completed", "validfrom"],
                    conditions={"token": uuid})

                # URL to launch the survey when on the Surveys screen
                url = self.url_surveys + survey["sid"] + "?token=" + uuid
                user_surveys.append({
                    "sid": survey["sid"],
                    "title": survey["surveyls_title"],
                    "expires": survey["expires"],
                    "active": survey["active"],
                    "completed": result[0]["completed"],
                    "received": result[0]["validfrom"],
                    "url": url
                })
                survey_count = survey_count + 1
            except:
                logging.warning("No %s in survey %s" % (uuid, survey['sid']))

        logging.debug("There are %s user surveys" % (survey_count, ))
        return {"survey_count": survey_count, "surveys": user_surveys}
import pandas as pd  #For data frames in a format PowerBI understands
from limesurveyrc2api.limesurvey import LimeSurvey  #To talk to LimeSurvey API
from limesurveyrc2api.exceptions import LimeSurveyError
import base64  #To convert base64 encoded data
import io  #To convert a string to a buffer for pandas to read

#Limesurvey details - change these to match your Survey
remotecontrolurl = "http://localhost/limesurvey/index.php/admin/remotecontrol"
limeuser = "******"
limepasswd = "password"
surveyid = "1"

#Code to call the LimeSurvey API to extract data

#Connect to LimeSurvey
lime = LimeSurvey(url=remotecontrolurl, username=limeuser)
lime.open(password=limepasswd)
#Read using the survey export responses API call
result = lime.survey.export_responses(survey_id=surveyid,
                                      document_type='csv',
                                      heading_type='full',
                                      response_type='long')
#Convert data to a pandas data frame
surveydata = pd.read_csv(io.StringIO(base64.b64decode(result).decode("utf-8")),
                         sep=';')
print(surveydata)
#Read using the token list participants API call
attlist = []
for x in range(1, 255):
    attlist.append("attribute_" + str(x))
result = lime.token.list_participants(survey_id=surveyid,