예제 #1
0
    async def join(self, ctx, code:str=None):
        account, first_time = utils.get_profile(ctx.author)
        chosen_class = config.CLASSES.find_one({'code': code})
        if chosen_class is not None:
            if chosen_class['owner'] != ctx.author.id:
                if chosen_class['code_joining']:
                    if ctx.author.id not in chosen_class['members']:
                        config.CLASSES.update_one({'code': code}, {'$push': {'members': ctx.author.id}})
                        embed=discord.Embed(title=f"{utils.emoji('plus')} Class Joined", description=f"You have enrolled in **{chosen_class['name']}**.\nYou can see information about the class by typing `d!class {chosen_class['code']}`", color=config.MAINCOLOR)
                        await ctx.send(embed=embed)
                        teacher = self.bot.get_user(chosen_class['owner'])
                        if teacher is not None and chosen_class['notifications']:
                            config.NOTIFICATIONS.insert_one({'date': datetime.datetime.utcnow(),
                                                             'title': f"{utils.emoji('bell')} Class Notification",
                                                             'content': f"A student named {ctx.author.name} ({str(ctx.author.id)}) has enrolled in {chosen_class['name']} [{chosen_class['code']}]",
                                                             'footer': f"to disable notifications type 'd!class {chosen_class['code']} notifications'",
                                                             'footer_icon': "https://cdn.discordapp.com/emojis/732116410553073674.png?v=1",
                                                             'reciever': teacher.id})
                    else:
                        embed = discord.Embed(title=f"{utils.emoji('cross')} You are already enrolled in this class", color=config.MAINCOLOR)
                        await ctx.send(embed=embed)
                else:
                    embed = discord.Embed(title=f"{utils.emoji('cross')} That class does not exist", color=config.MAINCOLOR)
                    await ctx.send(embed=embed)

            else:
                embed = discord.Embed(title=f"{utils.emoji('cross')} A Teacher cannot join their own class", color=config.MAINCOLOR)
                await ctx.send(embed=embed)
        else:
            embed = discord.Embed(title=f"{utils.emoji('cross')} That class does not exist", color=config.MAINCOLOR)
            await ctx.send(embed=embed)
예제 #2
0
 def run(self):
     profile, proxy = get_profile(self.profile), get_proxy(self.proxies)
     if profile == None:
         self.status_signal.emit({
             "msg": "Invalid profile",
             "status": "error"
         })
         return
     if proxy == None:
         self.status_signal.emit({
             "msg": "Invalid proxy list",
             "status": "error"
         })
         return
     if self.site == "Walmart":
         Walmart(self.task_id, self.status_signal, self.image_signal,
                 self.product, profile, proxy, self.monitor_delay,
                 self.error_delay, self.max_price)
     elif self.site == "Bestbuy":
         BestBuy(self.task_id, self.status_signal, self.image_signal,
                 self.product, profile, proxy, self.monitor_delay,
                 self.error_delay)
     elif self.site == "Target":
         Target(self.task_id, self.status_signal, self.image_signal,
                self.product, profile, proxy, self.monitor_delay,
                self.error_delay)
예제 #3
0
 def run(self):
     profile, proxy = get_profile(self.profile), get_proxy(self.proxies)
     if profile is None:
         self.status_signal.emit({
             "msg": "Invalid profile",
             "status": "error"
         })
         return
     if proxy is None:
         self.status_signal.emit({
             "msg": "Invalid proxy list",
             "status": "error"
         })
         return
     if self.site == "Walmart":
         Walmart(self.task_id, self.status_signal, self.image_signal,
                 self.wait_poll_signal, self.wait_condition, self.product,
                 profile, proxy, self.monitor_delay, self.error_delay,
                 self.max_price)
     elif self.site == "Bestbuy":
         BestBuy(self.status_signal, self.image_signal, self.product,
                 profile, proxy, self.monitor_delay,
                 self.error_delay)  #TODO: Readd Discord Webhook
     elif self.site == "Target":
         Target(self.task_id, self.status_signal, self.image_signal,
                self.product, profile, proxy, self.monitor_delay,
                self.error_delay)
     elif self.site == "GameStop":
         GameStop(self.task_id, self.status_signal, self.image_signal,
                  self.product, profile, proxy, self.monitor_delay,
                  self.error_delay, self.max_price)
예제 #4
0
 def run(self):
     profile = get_profile(self.profile)
     if profile == None:
         self.status_signal.emit({"msg":"Invalid profile","status":"error"})
         return
     if self.site == "Walmart":
         Walmart(self.status_signal,self.image_signal,self.product,profile,self.monitor_delay,self.error_delay,self.max_price)
예제 #5
0
 def load_profile(self):
     profile_name = self.loadprofile_box.currentText()
     p = get_profile(profile_name)
     if p is not None:
         self.profilename_edit.setText(p["profile_name"])
         self.shipping_fname_edit.setText(p["shipping_fname"])
         self.shipping_lname_edit.setText(p["shipping_lname"])
         self.shipping_email_edit.setText(p["shipping_email"])
         self.shipping_phone_edit.setText(p["shipping_phone"])
         self.shipping_address1_edit.setText(p["shipping_a1"])
         self.shipping_address2_edit.setText(p["shipping_a2"])
         self.shipping_city_edit.setText(p["shipping_city"])
         self.shipping_zipcode_edit.setText(p["shipping_zipcode"])
         self.shipping_country_box.setCurrentIndex(self.shipping_country_box.findText(p["shipping_country"]))
         self.shipping_state_box.setCurrentIndex(self.shipping_state_box.findText(p["shipping_state"]))
         self.billing_fname_edit.setText(p["billing_fname"])
         self.billing_lname_edit.setText(p["billing_lname"])
         self.billing_email_edit.setText(p["billing_email"])
         self.billing_phone_edit.setText(p["billing_phone"])
         self.billing_address1_edit.setText(p["billing_a1"])
         self.billing_address2_edit.setText(p["billing_a2"])
         self.billing_city_edit.setText(p["billing_city"])
         self.billing_zipcode_edit.setText(p["billing_zipcode"])
         self.billing_country_box.setCurrentIndex(self.billing_country_box.findText(p["billing_country"]))
         self.billing_state_box.setCurrentIndex(self.billing_state_box.findText(p["billing_state"]))
         self.cardnumber_edit.setText(p["card_number"])
         self.cardmonth_box.setCurrentIndex(self.cardmonth_box.findText(p["card_month"]))
         self.cardyear_box.setCurrentIndex(self.cardyear_box.findText(p["card_year"]))
         self.cardtype_box.setCurrentIndex(self.cardtype_box.findText(p["card_type"]))
         self.cardcvv_edit.setText(p["card_cvv"])
     return
예제 #6
0
def user_set_profile(sender, **kwargs):
    user = kwargs['instance']
    try:
        profile = get_profile(user.username)
        profile.user = user
        models.Model.save(profile)
    except Exception, e:
        pass
    def start(self, name):
        username = config('FACEBOOK_USER', default='')
        password = config('FACEBOOK_PASSWORD', default='')

        driver = webdriver.Firefox(firefox_profile=get_profile())
        driver.get('https://www.facebook.com/')
        driver.execute_script(f'document.getElementById("email").value = "{username}"')
        driver.execute_script(f'document.getElementById("pass").value = "{password}"')
        driver.find_element_by_id('loginbutton').click()
        time.sleep(2)

        driver.get(f"https://www.facebook.com/pg/{name.uuid}/posts/?ref=page_internal")

        i = 1
        for _ in range(self.np_posts):
            m = i * 10000
            driver.execute_script(f"window.scrollTo(0, {m})")
            time.sleep(1)
            i += 1

        for _ in range(self.np_comments):
            try:
                links = driver.find_elements_by_class_name('UFIPagerLink')
                for link in links:
                    link.click()
                    time.sleep(.5)
            except Exception as e:
                print(f'ERROR: UFIPagerLink not found : {e}')

        data = {
            'name': name.name,
            'comments': []
        }

        feeds = driver.find_elements_by_class_name('UFICommentContentBlock')
        for feed in feeds:
            try:
                upost = feed.find_element_by_class_name('UFICommentActorAndBody')
                username = upost.find_element_by_class_name('UFICommentActorName')
                comment = upost.find_element_by_class_name('UFICommentBody')
                dt = feed.find_element_by_class_name('UFISutroCommentTimestamp')

                if username and comment:
                    username = username.text.strip()
                    comment = comment.text.strip()
                    tm = int(dt.get_attribute('data-utime'))

                    data['comments'].append({
                        'hash': hashlib.sha256((username + '|' + comment).encode('ascii', 'ignore')).hexdigest(),
                        'username': username,
                        'data': time.strftime("%d/%m/%Y %H:%M", time.localtime(tm)),
                        'timestamp': tm,
                        'comment': comment
                    })
            except Exception as e:
                print(f'ERROR: username or comment not found : {e}')
        self.results['data'].append(data)
        driver.close()
예제 #8
0
def list_clusters(proxy):
    """List the clusters that currently exist in girder."""
    print('Listing clusters:')

    keys = [key('name'), key('status'), key('_id'),
            get_profile(proxy.profiles)]
    headers = ['Name', 'Status', 'Cluster ID', 'Profile']

    print(tabulate([[f(c) for f in keys] for c in proxy.clusters],
                   headers=headers))
    print('\n')
예제 #9
0
    def _set_rendering_info(self):
        self.dest_file = path = os.path.join(self.options.dest,
                                             self.classname.replace(".render.", os.sep).
                                             replace(".", os.sep))
        utils.mkdir(os.path.dirname(urlparse.urlsplit(self.dest_file).path))
        if not utils.isuri(self.dest_file):
            self.dest_file = utils.path2url(self.dest_file)

        profile = utils.get_profile(self.combination,
                                    video_restriction="video/x-raw,format=I420")
        self.add_arguments("-f", profile, "-o", self.dest_file)
예제 #10
0
def test_process_other_id_records(app, mocker):
    """Test create or update researcher other id."""
    mocker.patch("orcid_hub.utils.send_email", send_mail_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_external_identifierv3",
        create_or_update_fund_mock)
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile())
    org = app.data["org"]
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)

    UserOrg.create(user=u, org=org)

    t = Task.create(org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.OTHER_ID)

    OtherIdRecord.create(task=t,
                         type="grant_number",
                         value="xyz",
                         url="https://xyz.com",
                         relationship="SELF",
                         is_active=True,
                         status="email sent",
                         first_name="Test",
                         last_name="Test",
                         email="*****@*****.**",
                         visibility="PUBLIC",
                         display_index=1)

    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/person/update",
                      access_token="Test_token")
    utils.process_other_id_records()
    record = OtherIdRecord.get(email="*****@*****.**")
    assert 12399 == record.put_code
    assert "12344" == record.orcid
    def start(self, hashtag):

        driver = webdriver.Firefox(firefox_profile=get_profile())
        driver.get(f"https://twitter.com/hashtag/{hashtag}")
        time.sleep(1)

        try:
            login = driver.find_element_by_class_name('dropdown-signin')
            login.click()
            ultimas = driver.find_elements_by_class_name(
                'AdaptiveFiltersBar-target')
            ultimas[1].click()
            time.sleep(5)
        except Exception as e:
            print(f'ERROR: AdaptiveFiltersBar-target not found : {e}')

        for _ in range(self.np_posts):
            driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(3)

        data = {'hashtag': hashtag, 'comments': []}

        tweets = driver.find_elements_by_class_name('tweet')
        for tweet in tweets:
            try:
                username = tweet.find_element_by_class_name('username')
                comment = tweet.find_element_by_class_name('tweet-text')
                dt = tweet.find_element_by_class_name('_timestamp')

                if username and comment:
                    username = username.text.strip()
                    comment = comment.text.strip()
                    tm = int(dt.get_attribute('data-time'))

                    data['comments'].append({
                        'hash':
                        hashlib.sha256((username + '|' + comment).encode(
                            'ascii', 'ignore')).hexdigest(),
                        'username':
                        username,
                        'data':
                        time.strftime("%d/%m/%Y %H:%M", time.localtime(tm)),
                        'timestamp':
                        tm,
                        'comment':
                        comment
                    })
            except Exception as e:
                print(f'ERROR: username or comment not found : {e}')
        self.results['data'].append(data)
        driver.close()
예제 #12
0
def list_volumes(proxy):
    """List the volumes currently defined in girder."""
    print('Listing volumes:')

    keys = [key('name'), get_profile(proxy.profiles), key('_id'),
            key('size'), key('status'), key('type'), key('zone')]

    headers = ['Name', 'Profile', 'Volume ID',
               'Size', 'Status', 'Type', 'Zone']

    print(tabulate([[f(v) for f in keys] for v in proxy.volumes],
                   headers=headers))
    print('\n')
예제 #13
0
    def set_rendering_info(self):
        self.dest_file = path = os.path.join(self.options.dest,
                                             self.classname.replace(".transcode.", os.sep).
                                             replace(".", os.sep))
        utils.mkdir(os.path.dirname(urlparse.urlsplit(self.dest_file).path))
        if urlparse.urlparse(self.dest_file).scheme == "":
            self.dest_file = path2url(self.dest_file)

        try:
            video_restriction = G_V_PROTOCOL_VIDEO_RESTRICTION_CAPS[self.media_descriptor.get_protocol()]
        except KeyError:
            video_restriction = None

        profile = get_profile(self.combination, video_restriction=video_restriction)
        self.add_arguments("-o", profile)
예제 #14
0
def test_sync_profile(app, mocker):
    """Test sync_profile."""
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.update_employmentv3",
                 return_value=Mock(status=201,
                                   headers={'Location': '12344/XYZ/54321'}))
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.update_educationv3",
                 return_value=Mock(status=201,
                                   headers={'Location': '12344/XYZ/12345'}))

    org = Organisation.create(
        name="THE ORGANISATION:test_sync_profile",
        tuakiri_name="THE ORGANISATION:test_sync_profile",
        confirmed=True,
        orcid_client_id="APP-5ZVH4JRQ0C27RVH5",
        orcid_secret="Client Secret",
        city="CITY",
        country="COUNTRY",
        disambiguated_id="ID",
        disambiguation_source="SOURCE")
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org)
    access_token = "ACCESS-TOKEN"

    t = Task.create(org=org, task_type=TaskType.SYNC)
    api = MemberAPIV3(org=org)

    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: None)
    api.sync_profile(task=t, user=u, access_token=access_token)

    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/activities/update")
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: None)
    api.sync_profile(task=t, user=u, access_token=access_token)
    assert Log.select().count() > 0

    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile())
    api.sync_profile(task=t, user=u, access_token=access_token)
    last_log = Log.select().order_by(Log.id.desc()).first()
    assert "Successfully update" in last_log.message
예제 #15
0
    def test_get_profile_valid(self, mock_request_get, json_loads):

        get_return_value = MagicMock(
            content='{"valid_property_name": "valid_property_value"}',
            status_code=200
        )
        mock_request_get.return_value = get_return_value

        return_value = {
            'valid_property_name': 'valid_property_value'
        }

        json_loads.return_value = return_value

        details = utils.get_profile("some url")
        assert details == return_value
예제 #16
0
    async def create(self, ctx, *, name: str = None):
        account, first_time = utils.get_profile(ctx.author)

        teaching = list(utils.get_teaching_classes(ctx.author.id))
        if len(teaching) >= 8:
            embed = discord.Embed(title=f"{utils.emoji('card')} Premium",
                                  description=f"It looks like you have reached the maximum amount of classes you can teach. Premium allows for unlimited classes, and benifits all yoru students!\n\n- One time purchase\n- unlimited classes\n- tons of amazing features\n\nVisit [**Our website**](https://zombo.com) to purchase premium!",
                                  color=config.MAINCOLOR)
            await ctx.send(embed=embed)
            return

        if name is None:
            embed = discord.Embed(title=f"{utils.emoji('people')} Create a new class",
                                  description=f"Creating a class is simple. All you need to do is type the name of the class in this channel.",
                                  color=config.MAINCOLOR)
            embed.set_footer(text=f"Message timout in 60 seconds", icon_url="https://cdn.discordapp.com/emojis/732714132461191330.png?v=1")
            start_message = await ctx.send(embed=embed)

            def check(msg):
                return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id and len(msg.content) < 100

            try:
                name_message = await self.bot.wait_for('message', check=check, timeout=60.0)
                name = name_message.content
            except asyncio.TimeoutError:
                embed.description = f"Class creation has timed out. Please type `d!create` to try again."
                embed.set_footer()
                await start_message.edit(embed=embed)
                return

        new_class = {'name': name, 'code': gen_code(), 'owner': ctx.author.id, 'members': [], 'assignments': [], 'code_joining': True, 'link_joining': True, 'notifications': True, 'google_classroom': False}
        config.CLASSES.insert_one(new_class)

        embed = discord.Embed(title=f"{utils.emoji('checkb')} Class Created", color=config.MAINCOLOR, description=f"**{new_class['name']} [{new_class['code']}] has been created.**\n\nStudents can enroll by typing `d!join {new_class['code']}` or visiting https://discordclassroom.com/{new_class['code']}.\nView more information with `d!class {new_class['code']}`")
        await ctx.send(embed=embed)

        if account['is_student']:
            config.USERS.update({'user_id': ctx.author.id}, {'$set': {'is_student': False}})

        if account['teacher_notifications']:
            embed = discord.Embed(title=f"{utils.emoji('bell')} Class Notification",
                                  description=f"You will receive notifications from your class {new_class['name']} [{new_class['code']}] and can be turned off at any time.",
                                  color=config.MAINCOLOR)
            embed.set_footer(text=f"to disable notifications type 'd!class {new_class['code']} notifications'",
                             icon_url="https://cdn.discordapp.com/emojis/732116410553073674.png?v=1")
            await ctx.author.send(embed=embed)
예제 #17
0
    def run(self):
        profile, proxy = get_profile(self.profile), get_proxy(self.proxies)
        if profile is None:
            self.status_signal.emit({
                "msg": "Invalid profile",
                "status": "error"
            })
            return
        if proxy is None:
            self.status_signal.emit({
                "msg": "Invalid proxy list",
                "status": "error"
            })
            return

        if self.site == "Bestbuy":
            BestBuy(self.status_signal, self.image_signal, self.product,
                    profile, proxy, self.monitor_delay, self.error_delay)
예제 #18
0
def collect_profiles(repo_slugs):
    for repo_slug in repo_slugs:
        logging.info(repo_slug)
        try:
            assignees = utils.get_assignees(repo_slug)
        except KeyboardInterrupt:
            raise
        except:
            logging.warning("Failed to get assignees for %s", repo_slug)
            continue

        for assignee in assignees.index:
            logging.info("\t%s", assignee)
            try:
                profile = utils.get_profile(assignee)
            except KeyboardInterrupt:
                raise
            except:
                logging.warning("\tFailed to get profile for %s", assignee)
예제 #19
0
def test_affiliation_records(client, mocker):
    """Test affiliation records processing."""
    user = client.data["admin"]
    client.login(user, follow_redirects=True)

    with open(os.path.join(data_path, "affiliations.csv"), "rb") as f:
        resp = client.post(
            "/load/task/AFFILIATION",
            data={"file_": (f, "affiliations.csv")},
            follow_redirects=True,
        )
    assert resp.status_code == 200
    assert b"55561720" in resp.data
    assert b"208013283/01" in resp.data
    task = Task.get(filename="affiliations.csv")
    assert task.records.count() == 4

    send = mocker.patch("emails.message.MessageSendMixin.send")
    mocker.patch(
        "orcid_hub.orcid_client.MemberAPIV3.get_record",
        lambda s: get_profile(org=s.org, user=s.user),
    )
    urlopen = mocker.patch(
        "urllib3.poolmanager.PoolManager.urlopen",
        return_value=Mock(status_code=201,
                          headers={"Location: /record/424242"}),
    )

    resp = client.post("/activate_all/?url=/affiliations",
                       data=dict(task_id=task.id))
    assert resp.status_code == 302
    assert resp.location.endswith("/affiliations")

    urlopen.assert_called()
    for (args, kwargs) in urlopen.call_args_lis:
        assert args[0] == "PUT"

    send.assert_called()
    assert UserInvitation.select().count() == 1

    resp = client.get(f"/admin/affiliationrecord/?task_id={task.id}")
    assert b"555" in resp.data
예제 #20
0
    async def note(self, ctx, *, note: str = None):
        account, first_time = utils.get_profile(ctx.author)
        if note is None:
            embed = discord.Embed(
                title=f"{utils.emoji('news')} Note",
                description=
                f"Reply with a new note to change the note shown on your profile.\n\n*reply with `cancel` to cancel*",
                color=config.MAINCOLOR)
            embed.set_footer(
                text="Message timout in 60 seconds",
                icon_url=
                "https://cdn.discordapp.com/emojis/732714132461191330.png?v=1")
            start_message = await ctx.send(embed=embed)

            def check(msg):
                return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id and len(
                    msg.content) < 100

            try:
                note_message = await self.bot.wait_for('message',
                                                       check=check,
                                                       timeout=60.0)
                if note_message.content.lower() == "cancel":
                    embed.description = "Note has not been changed."
                    embed.set_footer()
                    await start_message.edit(embed=embed)
                    return
                note = note_message.content
            except asyncio.TimeoutError:
                embed.description = "Note change has timed out. Please type `d!note` to try again."
                embed.set_footer()
                await start_message.edit(embed=embed)
                return
        config.USERS.update({'user_id': ctx.author.id},
                            {'$set': {
                                'note': note
                            }})
        await ctx.send(embed=discord.Embed(
            title=f"{utils.emoji('checkb')} Note has been changed!"))
예제 #21
0
def test_create_or_update_property_record(app, mocker):
    """Test create or update researcher keyword, researcher url, other name and country"""
    mocker.patch("orcid_hub.utils.send_email", send_mail_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_keywordv3",
        create_or_update_fund_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_researcher_urlv3",
        create_or_update_fund_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_other_namev3",
        create_or_update_fund_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_addressv3",
        create_or_update_fund_mock)
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile())
    org = app.data["org"]
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)

    UserOrg.create(user=u, org=org)
    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/person/update",
                      access_token="Test_token")

    t = Task.create(id=12,
                    org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.PROPERTY)

    PropertyRecord.create(task=t,
                          type="KEYWORD",
                          is_active=True,
                          status="email sent",
                          first_name="Test",
                          last_name="Test",
                          email="*****@*****.**",
                          visibility="PUBLIC",
                          value="dummy name",
                          display_index=1)

    PropertyRecord.create(task=t,
                          type="COUNTRY",
                          is_active=True,
                          status="email sent",
                          first_name="Test",
                          last_name="Test",
                          email="*****@*****.**",
                          visibility="PUBLIC",
                          value="IN",
                          display_index=1)

    PropertyRecord.create(task=t,
                          type="URL",
                          is_active=True,
                          status="email sent",
                          first_name="Test",
                          last_name="Test",
                          email="*****@*****.**",
                          visibility="PUBLIC",
                          name="url name",
                          value="https://www.xyz.com",
                          display_index=1)

    PropertyRecord.create(task=t,
                          type="NAME",
                          is_active=True,
                          status="email sent",
                          first_name="Test",
                          last_name="Test",
                          email="*****@*****.**",
                          visibility="PUBLIC",
                          value="dummy name",
                          display_index=1)

    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    utils.process_property_records()
    keyword_record = PropertyRecord.get(email="*****@*****.**",
                                        type="KEYWORD")
    assert 12399 == keyword_record.put_code
    assert "12344" == keyword_record.orcid
    address_record = PropertyRecord.get(email="*****@*****.**",
                                        type="COUNTRY")
    assert 12399 == address_record.put_code
    assert "12344" == address_record.orcid
    url_record = PropertyRecord.get(email="*****@*****.**",
                                    type="URL")
    assert 12399 == url_record.put_code
    assert "12344" == url_record.orcid
    other_name_record = PropertyRecord.get(email="*****@*****.**",
                                           type="NAME")
    assert 12399 == other_name_record.put_code
    assert "12344" == other_name_record.orcid
예제 #22
0
    async def profile(self, ctx, user: discord.Member = None):
        owner = False
        if user is None:
            user = ctx.author
            owner = True
        account, first_time = utils.get_profile(user)
        embed = discord.Embed(
            title=f"{utils.emoji('enter')} {user.name}'s Profile",
            color=config.MAINCOLOR)
        embed.set_thumbnail(url=str(user.avatar_url))
        account_classes = list(utils.get_user_classes(ctx.author.id))
        account_teaching_classes = list(
            utils.get_teaching_classes(ctx.author.id))

        if owner and account['is_student'] and len(account_classes) < 1:
            embed.set_footer(
                text="Are you a teacher? Make sure to type 'd!class'",
                icon_url=
                "https://cdn.discordapp.com/emojis/732116410553073674.png?v=1")
        if account['note'] is None:
            embed.add_field(
                name=f"{utils.emoji('news')} Note",
                value=f"{user.name}'s Note can be set using `d!note`",
                inline=False)
        else:
            embed.add_field(name=f"{utils.emoji('news')} Note",
                            value=f"{account['note']}",
                            inline=False)

        if account['google_classroom'] is not None:
            embed.add_field(
                name=f"{utils.emoji('people')} Google Classroom",
                value=
                f"{account['google_classroom']} {utils.emoji('check_verify')}",
                inline=False)
        else:
            if owner:
                embed.add_field(
                    name=f"{utils.emoji('people')} Google Classroom",
                    value=
                    f"{utils.emoji('cross')} Not Linked. [**Link now**](https://discordclassroom.com/googleclassroom)",
                    inline=False)
            else:
                embed.add_field(
                    name=f"{utils.emoji('people')} Google Classroom",
                    value=f"{utils.emoji('cross')} Not Linked.",
                    inline=False)

        classes_string = ""
        if len(account_classes) > 0:
            classes_string += f"{str(len(account_classes))} Classes joined"
        if len(account_teaching_classes) > 0:
            classes_string += f"\n{str(len(account_teaching_classes))} Classes teaching"
        if classes_string != "":
            embed.add_field(name=f"{utils.emoji('inv')} Classes",
                            value=classes_string,
                            inline=True)

        if account['is_student']:
            embed.add_field(name=f"{utils.emoji('auth')} Role",
                            value=f"Student",
                            inline=True)
        else:
            embed.add_field(name=f"{utils.emoji('auth')} Role",
                            value=f"Teacher",
                            inline=True)

        await ctx.send(embed=embed)
예제 #23
0
    def start(self, name):
        driver = webdriver.Firefox(firefox_profile=get_profile())
        driver.get(f"https://twitter.com/{name.uuid}")

        for _ in range(self.np_posts):
            driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(1)

        data = {'name': name.name, 'feed': []}

        feeds = []
        posts = driver.find_elements_by_xpath(
            '//*[@id="stream-items-id"]/li/div')
        for post in posts:
            link = post.get_attribute('data-permalink-path')
            if link:
                feeds.append('https://twitter.com%s' % link)

        for feed in feeds:
            feed_data = {
                'feed_views_retweets': 0,
                'feed_views_likes': 0,
                'comments': []
            }

            driver.get(feed)

            try:
                retweets = driver.find_element_by_class_name(
                    'request-retweeted-popup').text
                feed_data['feed_views_retweets'] = int(
                    retweets.replace('Retweets',
                                     '').replace(',', '').replace('.', ''))
                likes = driver.find_element_by_class_name(
                    'request-favorited-popup').text
                feed_data['feed_views_likes'] = int(
                    likes.replace('Likes', '').replace(',',
                                                       '').replace('.', ''))
            except Exception as e:
                print(f'ERROR: likes element not found : {e}')

            i = 1
            for _ in range(self.np_comments):
                m = i * 2000
                driver.execute_script(
                    f"document.getElementById('permalink-overlay').scrollTo(0, {m})"
                )
                time.sleep(1)
                i += 1

            replies = driver.find_elements_by_class_name(
                'ThreadedConversation-moreRepliesLink')
            for reply in replies:
                try:
                    reply.click()
                except Exception as e:
                    print(
                        f'ERROR: ThreadedConversation-moreRepliesLink element not found : {e}'
                    )
                time.sleep(.5)

            replies_feed = driver.find_element_by_class_name('replies-to')
            if replies_feed:
                user_posts = replies_feed.find_elements_by_class_name(
                    'content')
                for upost in user_posts:
                    try:
                        username = upost.find_element_by_class_name('username')
                        comment = upost.find_element_by_class_name(
                            'tweet-text')
                        dt = upost.find_element_by_class_name('_timestamp')

                        if username and comment:
                            username = username.text.strip()
                            comment = comment.text.strip()
                            tm = int(dt.get_attribute('data-time'))

                            feed_data['comments'].append({
                                'hash':
                                hashlib.sha256(
                                    (username + '|' + comment).encode(
                                        'ascii', 'ignore')).hexdigest(),
                                'username':
                                username,
                                'data':
                                time.strftime("%d/%m/%Y %H:%M",
                                              time.localtime(tm)),
                                'timestamp':
                                tm,
                                'comment':
                                comment
                            })
                    except Exception as e:
                        print(f'ERROR: username or comment not found : {e}')
            data['feed'].append(feed_data)

        self.results['data'].append(data)
        driver.close()
예제 #24
0
    def start(self, name):
        driver = webdriver.Firefox(firefox_profile=get_profile())
        driver.get(f"https://www.instagram.com/{name.uuid}/?hl=pt-br")

        for _ in range(self.np_posts):
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(1)

        feeds = []
        links = driver.find_elements_by_tag_name('a')
        for link in links:
            href = link.get_attribute('href')
            if f'taken-by={name.uuid}' in href:
                feeds.append(href)

        data = {
            'name': name.name,
            'feed': []
        }

        for feed in feeds:
            feed_data = {
                'feed_views_likes': 0,
                'comments': []
            }

            driver.get(feed)

            try:
                like = driver.find_element_by_xpath(
                    "/html/body/span/section/main/div/div/article/div[2]/section[2]/div/span/span")
                feed_data['feed_views_likes'] = int(like.text.replace(',', '').replace('.', ''))
            except Exception as e:
                print(f'ERROR: likes element not found : {e}')

            try:
                btn = driver.find_element_by_xpath("//button[contains(text(),'Load more comments')]")
                for _ in range(self.np_comments):
                    btn.click()
                    time.sleep(.5)
            except Exception as e:
                print(f'ERROR: No button to load more comments : {e}')

            try:
                user_posts = driver.find_elements_by_xpath('//ul/li/div/div/div')
                for upost in user_posts:
                    try:
                        username = upost.find_element_by_tag_name('a')
                        comment = upost.find_element_by_tag_name('span')
                        if username and comment:
                            username = username.text.strip()
                            comment = comment.text.strip()
                            feed_data['comments'].append({
                                'hash': hashlib.sha256((username + '|' + comment).encode('ascii', 'ignore')).hexdigest(),
                                'username': username,
                                'comment': comment
                            })
                    except Exception as e:
                        print(f'ERROR: username or comment not found : {e}')
            except Exception as e:
                print(f'ERROR: No Comments found : {e}')
            data['feed'].append(feed_data)

        self.results['data'].append(data)
        driver.close()
예제 #25
0
    async def dash(self, ctx, code:str=None, *, value:str=None):
        account, first_time = utils.get_profile(ctx.author)
        if code is None:
            embed = discord.Embed(title=f"{utils.emoji('inv')} Your Classes",
                                  color=config.MAINCOLOR)
            for aclass in utils.get_teaching_classes(ctx.author.id):
                classname = aclass['name']
                classcode = aclass['code']
                classowner = aclass['owner']
                embed.add_field(name=f"{utils.emoji('crown')} " + classname + " [" + classcode + "]",
                                value="Teacher: **You**\nStudents: " + str(len(aclass['members'])) + "\n",
                                inline=True)
            for aclass in utils.get_user_classes(ctx.author.id):
                classname = aclass['name']
                classcode = aclass['code']
                classowner = aclass['owner']
                embed.add_field(name=f"{utils.emoji('enter')} " + classname + " [" + classcode + "]",
                                value="Teacher: <@" + str(classowner) + ">\nClassmates: " + str(len(aclass['members'])) + "\n",
                                inline=True)
            embed.description = "*Use `d!join` to join and `d!create` to create a class.*"
            await ctx.send(embed=embed)
        else:
            the_class = config.CLASSES.find_one({'code': code})
            if the_class is None:
                embed = discord.Embed(title=f"{utils.emoji('cross')} That class does not exist",
                                      color=config.MAINCOLOR)
                await ctx.send(embed=embed)
            else:
                if value is None:
                    if ctx.author.id == the_class['owner'] or ctx.author.id in the_class['members']:
                        if ctx.author.id == the_class['owner']:
                            embed = discord.Embed(title=f"{utils.emoji('crown')} {the_class['name']} Info [**{the_class['code']}**]",description=f"Teacher: **You**\nClass Size: {str(len(the_class['members']))}", color = config.MAINCOLOR)
                        else:
                            embed = discord.Embed(title=f"{utils.emoji('inv')} {the_class['name']} Info [**{the_class['code']}**]",description=f"Teacher: <@{the_class['owner']}>\nClass size: {str(len(the_class['members']))}", color = config.MAINCOLOR)
                        mystring = f"No Students in class."
                        i = 1
                        for student in the_class['members']:
                            if i == 1:
                                mystring = ""
                            if i < len(the_class['members']):
                                if i % 3 == 0 and i != 0:
                                    mystring += f"<@{student}>\n"
                                else:
                                    mystring += f"<@{student}>, "
                            else:
                                mystring += f"<@{student}>"
                            i += 1
                        if the_class['link_joining']:
                            embed.add_field(name=f"{utils.emoji('enter')} Link Join", inline=False, value=f"[**Invite Link**](https://discordclassroom.com/{the_class['code']})")
                        embed.add_field(name=f"{utils.emoji('people')} Class Directory", value=mystring)
                        if ctx.author.id == the_class['owner']:
                            emoji_dict = {True: f"{utils.emoji('on')}", False: f"{utils.emoji('off')}"}
                            embed.add_field(name=f"{utils.emoji('settings')} Settings", inline=False, value=f"{emoji_dict[the_class['code_joining']]} Code joining\n{emoji_dict[the_class['link_joining']]} Link Joining\n{emoji_dict[the_class['notifications']]} Notifications\n{emoji_dict[the_class['google_classroom']]} Google Classroom Link\n{emoji_dict[account['premium']]} Premium Features\n\n*to toggle these values, type `d!class {the_class['code']} <value>`*")

                        await ctx.send(embed=embed)
                    else:
                        embed = discord.Embed(title=f"{utils.emoji('cross')} That class does not exist",
                                              color=config.MAINCOLOR)
                        await ctx.send(embed=embed)
                else:
                    value_dict = {"joining": "code_joining", "link": "link_joining", "notifications": "notifications", "gclassroom": "google_classroom"}
                    value = value.lower()
                    values = {"joining", "notifications", "gclassroom", "link"}
                    if ctx.author.id == the_class['owner']:
                        if value in values:
                            if the_class[value_dict[value]] == True:
                                config.CLASSES.update_one({'code': code}, {'$set': {value_dict[value]: False}})
                                embed = discord.Embed(title=f"{utils.emoji('off')} Setting **{value}** was turned Off.", color = config.MAINCOLOR)
                            else:
                                config.CLASSES.update_one({'code': code}, {'$set': {value_dict[value]: True}})
                                embed = discord.Embed(title=f"{utils.emoji('on')} Setting **{value}** was turned On.", color = config.MAINCOLOR)
                            await ctx.send(embed=embed)
                        else:
                            embed = discord.Embed(title=f"{utils.emoji('cross')} That value does not Exist.",description="Please try one of the following\nJoining,\nNotifications,\nGClassroom", color = config.MAINCOLOR)
                            await ctx.send(embed=embed)
                    elif ctx.author.id in the_class['members']:
                        embed = discord.Embed(title=f"{utils.emoji('cross')} Only the Teacher can change values.", color = config.MAINCOLOR)
                        await ctx.send(embed=embed)
                    else:
                        embed = discord.Embed(title=f"{utils.emoji('cross')} That class does not exist", color = config.MAINCOLOR)
                        await ctx.send(embed=embed)
예제 #26
0
def test_create_or_update_funding(app, mocker):
    """Test create or update funding."""
    mocker.patch("orcid_hub.utils.send_email", send_mail_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_fundingv3",
        create_or_update_fund_mock)
    org = app.data["org"]
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile(org=org))

    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="123",
                    confirmed=True,
                    organisation=org)

    UserOrg.create(user=u, org=org)

    t = Task.create(org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.FUNDING)

    fr = FundingRecord.create(task=t,
                              title="Test titile",
                              translated_title="Test title",
                              translated_title_language_code="hi",
                              type="GRANT",
                              organization_defined_type="Test org",
                              short_description="Test desc",
                              amount="1000",
                              currency="USD",
                              org_name="Test_orgname",
                              city="Test city",
                              region="Test",
                              url="url",
                              start_date=PartialDate.create("2003-07-14"),
                              end_date=PartialDate.create("2004-07-14"),
                              country="NZ",
                              disambiguated_id="Test_dis",
                              disambiguation_source="Test_source",
                              is_active=True)

    FundingInvitee.create(record=fr,
                          first_name="Test",
                          email="*****@*****.**",
                          visibility="PUBLIC",
                          orcid="123")

    ExternalId.create(record=fr,
                      type="Test_type",
                      value="Test_value",
                      url="Test",
                      relationship="SELF")

    FundingContributor.create(record=fr,
                              orcid="1213",
                              role="LEAD",
                              name="Contributor",
                              email="*****@*****.**")

    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/activities/update",
                      access_token="Test_token")

    utils.process_funding_records()
    funding_invitees = FundingInvitee.get(orcid="12344")
    assert 12399 == funding_invitees.put_code
    assert "12344" == funding_invitees.orcid
예제 #27
0
def test_sync_profile(app, mocker):
    """Test sync_profile."""
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.update_employmentv3",
        return_value=Mock(status=201, headers={'Location': '12344/XYZ/54321'}))
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.update_educationv3",
        return_value=Mock(status=201, headers={'Location': '12344/XYZ/12345'}))

    def sync_profile_mock(*args, **kwargs):
        utils.sync_profile(*args, **kwargs)
        return Mock(id="test-test-test-test")

    mocker.patch("orcid_hub.utils.sync_profile.queue", sync_profile_mock)

    org = Organisation.create(
        name="THE ORGANISATION:test_sync_profile",
        tuakiri_name="THE ORGANISATION:test_sync_profile",
        confirmed=True,
        orcid_client_id="APP-5ZVH4JRQ0C27RVH5",
        orcid_secret="Client Secret",
        city="CITY",
        country="NZ",
        disambiguated_id="ID",
        disambiguation_source="SOURCE")
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org)

    utils.sync_profile(task_id=999999)

    t = Task.create(org=org, task_type=TaskType.SYNC)

    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: None)
    utils.sync_profile(task_id=t.id, delay=0)

    resp = get_profile()
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: resp)
    utils.sync_profile(task_id=t.id, delay=0)

    resp["activities-summary"]["educations"]["affiliation-group"] = []
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: resp)
    utils.sync_profile(task_id=t.id, delay=0)

    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.update_employmentv3",
                 side_effect=Exception("FAILED"))
    utils.sync_profile(task_id=t.id, delay=0)

    resp["activities-summary"]["employments"]["affiliation-group"][0][
        "summaries"][0]["employment-summary"]["source"] = None
    resp["activities-summary"]["employments"]["affiliation-group"][0][
        "summaries"][0]["employment-summary"]["source"] = None
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 lambda *args: resp)
    utils.sync_profile(task_id=t.id, delay=0)

    org.disambiguated_id = None
    org.save()
    utils.sync_profile(task_id=t.id, delay=0)

    assert Log.select().count() > 0
예제 #28
0
    def start(self, name):
        driver = webdriver.Firefox(firefox_profile=get_profile())
        driver.get(name.uuid)

        i = 1
        for _ in range(self.np_posts):
            m = i * 2000
            driver.execute_script(f"window.scrollTo(0, {m})")
            time.sleep(1)
            i += 1

        data = {
            'name': name.name,
            'feed': []
        }

        feeds = []
        posts = driver.find_elements_by_tag_name('ytd-grid-video-renderer')
        for post in posts:
            link = post.find_element_by_tag_name('a')
            if link:
                feeds.append(link.get_attribute('href'))

        for feed in feeds:
            feed_data = {
                'feed_views_views': 0,
                'feed_views_likes': 0,
                'feed_views_dislikes': 0,
                'comments': []
            }

            driver.get(feed)
            time.sleep(1)

            try:
                views = driver.find_element_by_class_name('view-count').text
                feed_data['feed_views_views'] = int(views.split()[0].replace(',', '').replace('.', ''))
            except Exception as e:
                print(f'ERROR: view count not found in tag : {e}')

            lds = driver.find_elements_by_tag_name('ytd-toggle-button-renderer')
            for ld in lds:
                try:
                    formatter = ld.find_element_by_tag_name('yt-formatted-string')
                    if formatter:
                        value = formatter.get_attribute('aria-label').strip()
                        if 'dislikes' in value:
                            feed_data['feed_views_dislikes'] = int(
                                value.replace(',', '').replace('dislikes', '').strip())
                        elif 'likes' in value:
                            feed_data['feed_views_likes'] = int(value.replace(',', '').replace('likes', '').strip())
                except Exception as e:
                    print(f'ERROR: Like / dislike not found in tag : {e}')

            # Let's try to pause the youtube video... trying 5 times!
            cpause = 5
            while cpause > 0:
                try:
                    pause = driver.find_element_by_class_name('ytp-play-button')
                    if pause:
                        cpause = 0
                        pause.click()
                except Exception as e:
                    cpause -= 1
                    time.sleep(1)

            i = 1
            driver.execute_script(f"window.scrollTo(0, 500)")
            time.sleep(2)
            for _ in range(self.np_comments):
                m = i * 2000
                driver.execute_script(f"window.scrollTo(0, {m})")
                time.sleep(1)
                i += 1

            replies = driver.find_elements_by_tag_name('ytd-expander')
            for reply in replies:
                if 'View' in reply.text.strip():
                    try:
                        reply.find_element_by_id('more').click()
                    except Exception as e:
                        print(f'ERROR: element not found : {e}')
                    time.sleep(.5)

            user_posts = driver.find_elements_by_tag_name('ytd-comment-thread-renderer')
            for upost in user_posts:
                try:
                    username = upost.find_element_by_id('author-text')
                    comment = upost.find_element_by_id('content')
                    if username and comment:
                        username = username.text.strip()
                        comment = comment.text.strip()
                        feed_data['comments'].append({
                            'hash': hashlib.sha256((username + '|' + comment).encode('ascii', 'ignore')).hexdigest(),
                            'username': username,
                            'comment': comment
                        })
                except Exception as e:
                    print(f'ERROR: username or comment not found : {e}')
            data['feed'].append(feed_data)

        self.results['data'].append(data)
        driver.close()
예제 #29
0
def test_create_or_update_work(app, mocker):
    """Test create or update work."""
    mocker.patch("orcid_hub.utils.send_email", send_mail_mock)
    mocker.patch("orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_workv3",
                 create_or_update_fund_mock)
    org = app.data["org"]
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile(org=org))

    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)

    UserOrg.create(user=u, org=org)

    t = Task.create(org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.WORK)

    wr = WorkRecord.create(task=t,
                           title="Test titile",
                           subtitle="Test titile",
                           translated_title="Test title",
                           translated_title_language_code="hi",
                           journal_title="Test titile",
                           short_description="Test desc",
                           citation_type="bibtex",
                           citation_value="Test",
                           type="BOOK_CHAPTER",
                           publication_date=PartialDate.create("2003-07-14"),
                           url="Test org",
                           language_code="en",
                           country="NZ",
                           org_name="Test_orgname",
                           city="Test city",
                           region="Test",
                           is_active=True)

    WorkInvitee.create(record=wr,
                       first_name="Test",
                       email="*****@*****.**",
                       orcid="12344",
                       visibility="PUBLIC")

    WorkExternalId.create(record=wr,
                          type="Test_type",
                          value="Test_value",
                          url="Test",
                          relationship="SELF")

    WorkContributor.create(record=wr,
                           contributor_sequence="first",
                           orcid="1213",
                           role="author",
                           name="xyz",
                           email="*****@*****.**")

    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/activities/update",
                      access_token="Test_token")

    utils.process_work_records()
    invitee = WorkInvitee.get(orcid="12344")
    assert 12399 == invitee.put_code
    assert "12344" == invitee.orcid
예제 #30
0
def test_create_or_update_peer_review(app, mocker):
    """Test create or update peer review."""
    mocker.patch("orcid_hub.utils.send_email", send_mail_mock)
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_peer_reviewv3",
        create_or_update_fund_mock)
    org = app.data["org"]
    mocker.patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                 return_value=get_profile(org=org))
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="12344",
                    confirmed=True,
                    organisation=org)

    UserOrg.create(user=u, org=org)

    t = Task.create(id=12,
                    org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.PEER_REVIEW)
    pr = PeerReviewRecord.create(
        task=t,
        review_group_id="issn:12131",
        reviewer_role="reviewer",
        review_url="xyz",
        review_type="REVIEW",
        subject_external_id_type="doi",
        subject_external_id_value="1212",
        subject_external_id_url="url/SELF",
        subject_external_id_relationship="SELF",
        subject_container_name="Journal title",
        subject_type="JOURNAL_ARTICLE",
        subject_name_title="name",
        subject_name_subtitle="subtitle",
        review_completion_date=PartialDate.create("2003-07-14"),
        subject_name_translated_title_lang_code="en",
        subject_name_translated_title="sdsd",
        subject_url="url",
        convening_org_name="THE ORGANISATION",
        convening_org_city="auckland",
        convening_org_region="auckland",
        convening_org_country="NZ",
        convening_org_disambiguated_identifier="123",
        convening_org_disambiguation_source="1212",
        is_active=True)

    PeerReviewInvitee.create(record=pr,
                             first_name="Test",
                             email="*****@*****.**",
                             orcid="12344",
                             visibility="PUBLIC")

    PeerReviewExternalId.create(record=pr,
                                type="Test_type",
                                value="122334_different",
                                url="Test",
                                relationship="SELF")

    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/activities/update",
                      access_token="Test_token")

    utils.process_peer_review_records()
    peer_review_invitees = PeerReviewInvitee.get(orcid=12344)
    assert 12399 == peer_review_invitees.put_code
    assert "12344" == peer_review_invitees.orcid
예제 #31
0
def init(profile):
    e = utils.get_profile(profile, key='engine')
    selectTTS(e)
    return engine(profile)
예제 #32
0
def test_create_or_update_affiliation(app, mocker):
    """Test create or update affiliation."""
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.update_employmentv3",
        return_value=Mock(status=201, headers={'Location': '12344/XYZ/12399'}))
    mocker.patch(
        "orcid_api_v3.api.DevelopmentMemberAPIV30Api.create_employmentv3",
        return_value=Mock(status=201, headers={'Location': '12344/XYZ/12399'}))
    send_email = mocker.patch("orcid_hub.utils.send_email")
    capture_event = mocker.patch(
        "sentry_sdk.transport.HttpTransport.capture_event")
    org = app.data["org"]
    u = User.create(email="*****@*****.**",
                    name="TEST USER",
                    roles=Role.RESEARCHER,
                    orcid="123",
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org)
    t = Task.create(org=org,
                    filename="xyz.json",
                    created_by=u,
                    updated_by=u,
                    task_type=TaskType.AFFILIATION)
    OrcidToken.create(user=u,
                      org=org,
                      scopes="/read-limited,/activities/update",
                      access_token="Test_token")
    UserInvitation.create(invitee=u,
                          inviter=u,
                          org=org,
                          task=t,
                          email="*****@*****.**",
                          token="xyztoken")

    u = User.create(email="*****@*****.**",
                    name="TEST USER 2",
                    roles=Role.RESEARCHER,
                    confirmed=True,
                    organisation=org)
    UserOrg.create(user=u, org=org)

    AffiliationRecord.create(is_active=True,
                             task=t,
                             local_id="Test",
                             first_name="Test",
                             last_name="Test",
                             email="*****@*****.**",
                             orcid="123112311231",
                             organisation="asdasd",
                             affiliation_type="staff",
                             role="Test",
                             department="Test",
                             city="Test",
                             state="Test",
                             country="NZ",
                             disambiguated_id="Test",
                             disambiguation_source="Test")
    AffiliationRecord.create(is_active=True,
                             task=t,
                             local_id="Test",
                             first_name="Test",
                             last_name="Test",
                             email="*****@*****.**",
                             orcid="123112311231",
                             organisation=org.name,
                             affiliation_type="staff",
                             role="Test",
                             department="Test",
                             city="Test",
                             state="Test",
                             country="NZ")
    AffiliationRecord.create(is_active=True,
                             task=t,
                             local_id="Test",
                             first_name="Test",
                             last_name="Test",
                             email="*****@*****.**",
                             orcid="123112311231",
                             organisation="ANOTHER ORG",
                             affiliation_type="staff",
                             role="Test",
                             department="Test",
                             city="Test",
                             state="Test",
                             country="NZ",
                             visibility="PUBLIC")
    AffiliationRecord.create(is_active=True,
                             task=t,
                             local_id="Test#2",
                             first_name="Test2",
                             last_name="Test2",
                             email="*****@*****.**",
                             organisation=org.name,
                             affiliation_type="staff")

    tasks = (Task.select(
        Task, AffiliationRecord, User,
        UserInvitation.id.alias("invitation_id"), OrcidToken).join(
            AffiliationRecord,
            on=(Task.id == AffiliationRecord.task_id).alias("record")).join(
                User,
                JOIN.LEFT_OUTER,
                on=((User.email == AffiliationRecord.email)
                    | (User.orcid == AffiliationRecord.orcid))).join(
                        Organisation,
                        JOIN.LEFT_OUTER,
                        on=(Organisation.id == Task.org_id)).join(
                            UserInvitation,
                            JOIN.LEFT_OUTER,
                            on=((UserInvitation.email
                                 == AffiliationRecord.email)
                                & (UserInvitation.task_id == Task.id))).
             join(OrcidToken,
                  JOIN.LEFT_OUTER,
                  on=((OrcidToken.user_id == User.id)
                      & (OrcidToken.org_id == Organisation.id)
                      & (OrcidToken.scopes.contains("/activities/update")))))
    app.config["SERVER_NAME"] = "orcidhub"
    for (task_id, org_id, user), tasks_by_user in groupby(
            tasks, lambda t: (
                t.id,
                t.org_id,
                t.record.user,
            )):
        with patch("orcid_hub.orcid_client.MemberAPIV3.get_record",
                   return_value=get_profile()
                   if user.orcid else None) as get_record:
            utils.create_or_update_affiliations(user=user,
                                                org_id=org_id,
                                                records=tasks_by_user)
            get_record.assert_any_call()
    affiliation_record = AffiliationRecord.select().order_by(
        AffiliationRecord.id).limit(1).first()
    assert 12399 == affiliation_record.put_code
    assert "12344" == affiliation_record.orcid
    assert ("Employment record was updated" in affiliation_record.status
            or "Employment record was created" in affiliation_record.status)
    capture_event.assert_called()
    send_email.assert_called_once()