示例#1
0
def updateentry() -> Any:
    if request.method == 'POST':
        data = request.get_json()
        module = data.get('module')
        entry_id = _str(data.get('entry_id', None))
        project = data.get('project_id', None)
        if project == "null":
            project = None
        project_to_group = {
            project.pid: project.group
            for project in Project.query.all()
        }
        new_entry = Entry(start_time=parseTimestamp(data['start_time']),
                          end_time=parseTimestamp(data.get('end_time', None)),
                          id=entry_id,
                          issue=data.get('issue_id', None),
                          project=project,
                          title=data.get('title', ''),
                          text=data.get('text', ""),
                          extra_data=data.get('extra_data', {}),
                          group=project_to_group.get(str(project), None))
        issue = None
        if new_entry.issue:
            issue = Issue.query.filter(Issue.uuid == new_entry.issue).first()

        parser = Parser(None, None)

        if not entry_id:
            # Check that create is allowed
            assert isinstance(parser.modules[module], AddEntryMixin)
            new_entry = parser.modules[module].create_entry(  # type: ignore
                new_entry=new_entry, issue=issue)
        else:
            # Check that update is allowed
            assert isinstance(parser.modules[module], UpdateEntryMixin)
            new_entry = parser.modules[module].update_entry(  # type: ignore
                entry_id=new_entry.id,
                new_entry=new_entry,
                issue=issue)
        data = "error"

        if new_entry:
            Entry.query.filter(Entry.id == new_entry.id).delete()
            new_entry.module = module
            db.session.merge(new_entry)
            db.session.commit()
            data = new_entry.to_dict()

        return json.dumps(data, default=json_serial)
    return None
示例#2
0
    def get_entries(self) -> List[Entry]:
        start_date = self.start_date
        end_date = self.end_date
        log = []
        provider = Provider()
        for group, data in settings.GIT.items():
            for repo_path in data.get('REPOS', []):
                for log_entry in provider.get_log_entries(repo_path):
                    if log_entry.actor.email not in settings.GIT['global'][
                            'EMAILS']:
                        continue
                    if not log_entry.message.startswith('commit'):
                        continue
                    message = ''.join(log_entry.message.split(':')[1:])
                    time = timestamp_to_datetime(log_entry.time)
                    if time < start_date or time > end_date:
                        continue

                    log.append(
                        Entry(
                            text="{} - {}".format(
                                repo_path.split('/')[-1], message),
                            start_time=time,
                        ))
        return log
示例#3
0
    def get_entries(self) -> List[Entry]:
        start_date = self.start_date
        end_date = self.end_date
        log = []
        provider = Provider()
        for group, data in settings.GIT.items():
            for repo_path in data.get('REPOS', []):
                for log_entry in provider.get_log_entries(
                        repo_path, start_date=start_date):
                    if log_entry.author.email not in settings.GIT['global'][
                            'EMAILS']:
                        logger.info(log_entry.author.email)
                        continue
                    time = git_time_to_datetime(log_entry.authored_datetime)
                    if time < start_date or time > end_date:
                        continue

                    log.append(
                        Entry(
                            text="{} - {}".format(
                                repo_path.split('/')[-1], log_entry.message),
                            start_time=time,
                            group=group,
                        ))
        return log
示例#4
0
def test_toggl_add_modify_delete(parser: Parser):
    parser.entries = parser.get_entries()
    entry = Entry(
        id="4",
        start_time=datetime.utcnow() - timedelta(hours=2),
        end_time=datetime.utcnow() - timedelta(hours=1),
        title="Toggl new entry (4)",
        project="10",
    )
    entry = parser.create_entry(entry, None)
    assert entry.id == "4"

    entry.title = "Toggl modified entry"
    entry = parser.update_entry("4", entry, None)
    assert entry.title == "Toggl modified entry"

    parser.delete_entry("4")
示例#5
0
 def _init_session(entry):
     return Entry(
         start_time=entry['time'],
         extra_data={
             'windows': {},
             'category': {'work': 0, 'leisure': 0}
         }
     )
示例#6
0
 def create_entry(self, new_entry: Entry, issue: Optional[Issue]) -> Entry:
     if not new_entry.project or new_entry.project == '0':
         new_entry.project = None
     if new_entry.end_time is None:
         raise ValueError("No end_time")
     entry = self.provider.workspace_request(
         'time-entries',
         data=json.dumps({
             'start': new_entry.start_time.isoformat() + 'Z',
             'end': new_entry.end_time.isoformat() + 'Z',
             'description': new_entry.title,
             'projectId': new_entry.project,
         }),
         method='POST'
     )
     return Entry(
         id=_str(entry['id']),
         start_time=parse_time(entry['timeInterval']['start']),
         end_time=parse_time(entry['timeInterval']['end']),
         title=entry['description'],
         project=entry['projectId'],
     )
示例#7
0
 def create_entry(self, new_entry: Entry, issue: Optional[Issue]) -> Entry:
     entry = self.push_session(session={
         'start_time': new_entry.start_time,
         'end_time': new_entry.end_time,
     },
                               name=new_entry.title,
                               project_id=new_entry.project)
     return Entry(
         id=_str(entry['id']),
         start_time=parse_time(entry['start']),
         end_time=parse_time(entry['stop']),
         title=entry['description'],
         project=entry.get('pid', None),
     )
示例#8
0
    def update_entry(self, entry_id: str, new_entry: Entry, issue: Optional[Issue]) -> Entry:
        updated_entry = self.push_session(
            session={
                'start_time': new_entry.start_time,
                'end_time': new_entry.end_time,
            },
            entry_id=entry_id,
            name=new_entry.title,
            project_id=new_entry.project
        )

        return Entry(
            id=_str(updated_entry['id']),
            start_time=parse_time(updated_entry['start']),
            end_time=parse_time(updated_entry['stop']),
            title=updated_entry['description'],
            project=_str(updated_entry.get('pid', None)),
            group=new_entry.group,
        )
示例#9
0
    def get_entries(self) -> List[Entry]:
        if self.start_date:
            params = {'start_date': self.start_date.isoformat() + "+00:00",
                      'end_date': self.end_date.isoformat() + "+00:00"}
        else:
            params = {}
        data = self.provider.request(
            'time_entries', params=params, method='GET'
        )
        time_entries = []
        for entry in data:
            time_entries.append(Entry(
                id=entry['id'],
                start_time=parse_time(entry['start']),
                end_time=parse_time(entry['stop']),
                title=entry.get('description', ''),
                project=entry.get('pid', None),
            ))

        return time_entries
示例#10
0
    async def async_parse_channel(self, provider, channel, user_id, users,
                                  group):
        logger.warning("Getting channel %s for group %s", channel['id'], group)
        history = await provider.api_call(
            "conversations.history",
            data={
                'channel': channel['id'],
                'oldest':
                (self.start_date - datetime(1970, 1, 1)).total_seconds(),
                'latest':
                (self.end_date - datetime(1970, 1, 1)).total_seconds()
            })
        # Get either Istant Message recipient or channel name
        if channel.get('is_im', False) and channel.get('user', ''):
            channel_info = users.get(channel.get('user', ''), None)
        else:
            channel_info = channel.get('name_normalized', channel['id'])

        for message in history['messages']:
            if message.get('user', '') == user_id:
                start_time = datetime.fromtimestamp(float(message['ts']))
                # "Guess" That the timestamp has an offset equal to settings.TIMEZONE
                if getattr(settings, 'TIMEZONE', None):
                    start_time = pytz.timezone("Europe/Helsinki").localize(
                        start_time).astimezone(pytz.utc).replace(tzinfo=None)
                # Replace @User id with the name
                for _user_id in users.keys():
                    if _user_id in message['text']:
                        message['text'] = message['text'].replace(
                            _user_id, users[_user_id])
                logger.warning(
                    "Found message %s",
                    "{} - {} \n {}".format(group, channel_info,
                                           message['text']))
                self.async_entries.append(
                    Entry(start_time=start_time,
                          title='',
                          text="{} - {} \n {}".format(group, channel_info,
                                                      message['text']),
                          group=group))
示例#11
0
    def get_entries(self) -> List[Entry]:

        if self.start_date:
            params = {'start': self.start_date.isoformat() + 'Z',
                      'end': self.end_date.isoformat() + 'Z'}
        else:
            params = {}

        time_entries = []
        data = self.provider.workspace_request(
            'user/{user_id}/time-entries'.format(
                user_id=self.user['id']
            ), params=params, method='GET'
        )
        for entry in data:
            time_entries.append(Entry(
                id=entry['id'],
                start_time=parse_time(entry['timeInterval']['start']),
                end_time=parse_time(entry['timeInterval']['end']),
                title=entry['description'],
                project=entry['projectId'],
            ))

        return time_entries
示例#12
0
 def _init_session(entry):
     return Entry(start_time=entry['time'],
                  extra_data={
                      'windows': {},
                      'group': {},
                  })
示例#13
0
    def get_entries(self) -> List[Entry]:
        # start_date, end_date = self.get_offset_dates()
        # if not start_date and not end_date:
        #     return []
        start_date = self.start_date
        end_date = self.end_date
        entries = []
        for group, group_data in settings.SLACK.items():

            slack_token = group_data['API_KEY']
            user_id = group_data['USER_ID']

            provider = Provider(slack_token)
            users_list = provider.api_call("users.list")
            users = {}
            for user in users_list['members']:
                users[user['id']] = (
                    user['profile'].get('first_name', 'NULL') + ' ' +
                    user['profile'].get('last_name', 'NULL'))
            channels = provider.api_call(
                "conversations.list",
                data={'types':
                      'public_channel,private_channel,mpim,im'})['channels']
            for channel in channels:
                history = provider.api_call(
                    "conversations.history",
                    data={
                        'channel':
                        channel['id'],
                        'oldest':
                        (start_date - datetime(1970, 1, 1)).total_seconds(),
                        'latest':
                        (end_date - datetime(1970, 1, 1)).total_seconds()
                    })

                # Get either Istant Message recipient or channel name
                if channel.get('is_im', False) and channel.get('user', ''):
                    channel_info = users.get(channel.get('user', ''), None)
                else:
                    channel_info = channel.get('name_normalized', 'Unknown')

                for message in history['messages']:
                    if message.get('user', '') == user_id:
                        start_time = datetime.fromtimestamp(
                            float(message['ts']))
                        # "Guess" That the timestamp has an offset equal to settings.TIMEZONE
                        if getattr(settings, 'TIMEZONE', None):
                            start_time = pytz.timezone(
                                "Europe/Helsinki").localize(
                                    start_time).astimezone(
                                        pytz.utc).replace(tzinfo=None)
                        # Replace @User id with the name
                        for _user_id in users.keys():
                            if _user_id in message['text']:
                                message['text'] = message['text'].replace(
                                    _user_id, users[_user_id])
                        entries.append(
                            Entry(start_time=start_time,
                                  title='',
                                  text="{} - {} \n {}".format(
                                      group, channel_info, message['text'])))
        return entries