예제 #1
0
    def test_get_document_url(self):
        resource_id = 'toto'
        url_expected = '{0}{1}'.format(
            settings.BASE_URL,
            reverse('website.views.embedded_document', args=[resource_id]))

        self.assertEqual(GoogleDriveHelper.get_document_url(resource_id),
                         url_expected)
예제 #2
0
def document_temp_share_task(document, user):
    logger.debug(u'Looking for a temporary share for training {0} and user {1}'.format(document.resource_id, user))

    trainingTempShares = TrainingTempShare.objects.filter(
        Q(user_invited=user) | Q(facebook_id=user.get_profile().facebook_id) | Q(email=user.email), training=document)

    if trainingTempShares.exists():
        logger.debug(u'Temporary share found for training {0} and user {1}'.format(document.resource_id, user))
        for trainingTempShare in trainingTempShares:
            if trainingTempShare.role == 'cowriters':
                if document.creator != user and user not in document.cowriters.all():
                    logger.debug(u'Adding co-writer for training {0} and user {1}'.format(document.resource_id, user))
                    document.cowriters.add(user)

                    if user in document.participants.all():
                        logger.debug(u'Remove participant for training {0} and user {1}'.format(document.resource_id, user))
                        document.participants.remove(user)
                    document.save()
                else:
                    logger.debug(u'User {0} is already cowriter on training {1}'.format(user, document.resource_id))
            elif trainingTempShare.role == 'participants':
                if document.creator != user and user not in document.participants.all() and user not in document.cowriters.all():
                    logger.debug(u'Adding participant for training {0} and user {1}'.format(document.resource_id, user))
                    document.participants.add(user)
                    document.save()
                else:
                    logger.debug(u'User {0} is already cowriter/participant on training {1}'.format(user, document.resource_id))
            trainingTempShare.delete()
    else:
        if document.creator != user and user not in document.cowriters.all() and user not in document.participants.all():
            logger.debug('Adding participant for training {0} and user {1}'.format(document.resource_id, user))
            document.participants.add(user)

            if Training.objects.filter(participants=user).count() == 1:
                logger.debug('Sending first participation mail')
                context = Context({'user': user,
                                   'document': {'url': GoogleDriveHelper.get_document_url(document.resource_id),
                                   'title': document.title},
                                   'ga_campaign_params': 'utm_source=unishared&utm_content=v1&utm_medium=e-mail&utm_campaign=new_document_participation_mail'})
                email_task.apply_async(
                    ["Yihaa, you participated in a collaborative document!", context, "new_document_participation_mail",
                     [user.email]])

        document.total_views += 1
        document.total_views_open25 += 1
        document.save()

        try:
            logger.debug('Adding participation for training {0} and user {1}'.format(document.resource_id, user))
            participation = TrainingParticipation.objects.get(user=user, training=document)
            participation.count += 1
            participation.save()
        except TrainingParticipation.DoesNotExist:
            TrainingParticipation.objects.create(user=user, training=document, count=1)
예제 #3
0
    def test_get_document_url(self):
        resource_id = 'toto'
        url_expected = '{0}{1}'.format(settings.BASE_URL, reverse('website.views.embedded_document', args=[resource_id]))

        self.assertEqual(GoogleDriveHelper.get_document_url(resource_id), url_expected)
예제 #4
0
    def run(self):
        logger = LoggingHelper.getDebugLogger()
        logger.debug('Looking for a temporary share for training {0} and user {1}'.format(self.training.resource_id, self.user))
        
        trainingShare = TrainingTempShare.objects.filter(Q(facebook_id=self.user.get_profile().facebook_id) | Q(email=self.user.email), training=self.training)
        if trainingShare.exists():
            logger.debug('Temporary share found for training {0} and user {1}'.format(self.training.resource_id, self.user))
            if self.training.creator != self.user and self.user not in self.training.cowriters.all():     
                logger.debug('Adding co-writer for training {0} and user {1}'.format(self.training.resource_id, self.user))
                self.training.cowriters.add(self.user) 
                
                if self.user in self.training.participants.all():
                    logger.debug('Remove participant for training {0} and user {1}'.format(self.training.resource_id, self.user))
                    self.training.participants.remove(self.user)
                
            trainingShare.delete()
        elif self.training.creator != self.user and self.user not in self.training.cowriters.all() and self.user not in self.training.participants.all():
            logger.debug('Adding participant for training {0} and user {1}'.format(self.training.resource_id, self.user))
            self.training.participants.add(self.user)

            if Training.objects.filter(participants=self.user).count() == 1:
                logger.debug('Sending first participation mail')
                context = Context({'username': self.user.username, 'first_name' : self.user.first_name, 'profile_url' : ProfileHelper.get_profile_url(self.user.username), 'document_url' : GoogleDriveHelper.get_document_url(self.training.resource_id), 'document_title' : self.training.title, 'ga_campaign_params' : 'utm_source=unishared&utm_content=v1&utm_medium=e-mail&utm_campaign=new_document_participation_mail'})
                email_task.apply_async(["Yihaa, you participated in a collaborative document!", context, "new_document_participation_mail", [self.user.email]])
        
        try:
            logger.debug('Adding participation for training {0} and user {1}'.format(self.training.resource_id, self.user))
            participation = TrainingParticipation.objects.get(user=self.user, training=self.training)
            participation.count += 1
            participation.save()
        except TrainingParticipation.DoesNotExist:
            TrainingParticipation.objects.create(user=self.user, training=self.training, count=1)
예제 #5
0
def live_detection_change_feed(last_result):
    logger.debug('Starting live detection with change feed')

    client = GoogleDriveHelper.get_docs_client()

    params = {'includeDeleted' : False}
    if last_result and last_result['startChangeId']:
        logger.debug('Last change id : {0}'.format(last_result['startChangeId']))
        params['startChangeId'] = last_result['startChangeId']

    result = client.changes().list(**params).execute()

    task_result = {'startChangeId' : int(result['largestChangeId']) + 1, 'items' : []}

    for item in result['items']:
        resource_id = item['file']['id']
        updated = parser.parse(item['file']['modifiedDate'])
        title = item['file']['title']

        try:
            last_entries = None
            if last_result:
                last_entries = [last_entry for last_entry in last_result['items'] if last_entry['document_id'] == resource_id]
            last_entry = last_entries[0] if last_entries and len(last_entries) > 0 else None

            document = Training.objects.get(resource_id=resource_id)

            logger.debug('Document recently modified : %s', resource_id)

            if document.title != title:
                logger.debug('Updating title of document {0}'.format(resource_id))
                document.title=title

            updated = calendar.timegm(updated.utctimetuple())
            document.last_updated = updated

            if last_entry:
                logger.debug('Previous entry found')
                logger.debug('Last entry : {0}'.format(last_entry))
                if last_entry['live'] is None:
                    logger.debug('Enabling live in DB for %s', resource_id)

                    document.is_live = True
                    document.is_displayed = True

                    email_task.apply_async(
                        ['Document live', Context({'document_url': GoogleDriveHelper.get_document_url(resource_id)}),
                         'document_live', [a[1] for a in settings.ADMINS], None, 'gmail'])
                else:
                    logger.debug('Document already live %s', resource_id)

                task_result['items'].append({'document_id': resource_id, 'live': True})
            else:
                logger.debug('No previous entry found')
                logger.debug('Creating entry %s', resource_id)
                task_result['items'].append({'document_id': resource_id, 'live': None})

            document.save()
        except Training.DoesNotExist:
            logger.debug('Unexisting resource {0}'.format(resource_id))
        except Exception:
            LoggingHelper.getErrorLogger().error('An error occurred while detecting live', exc_info=1)

    logger.debug('Disabling documents not live anymore')
    Training.objects.filter(~Q(resource_id__in=[item['file']['id'] for item in result['items']]), is_live=True).update(is_live=False)

    logger.debug('Result : %s', task_result)
    live_detection_change_feed.apply_async([task_result], eta=timezone.now()+timedelta(minutes=5))
    return task_result
예제 #6
0
파일: tasks.py 프로젝트: dylan-wu/unishared
def live_detection_change_feed(last_result):
    logger.debug('Starting live detection with change feed')

    client = GoogleDriveHelper.get_docs_client()

    params = {'includeDeleted': False}
    if last_result and last_result['startChangeId']:
        logger.debug('Last change id : {0}'.format(
            last_result['startChangeId']))
        params['startChangeId'] = last_result['startChangeId']

    result = client.changes().list(**params).execute()

    task_result = {
        'startChangeId': int(result['largestChangeId']) + 1,
        'items': []
    }

    for item in result['items']:
        resource_id = item['file']['id']
        updated = parser.parse(item['file']['modifiedDate'])
        title = item['file']['title']

        try:
            last_entries = None
            if last_result:
                last_entries = [
                    last_entry for last_entry in last_result['items']
                    if last_entry['document_id'] == resource_id
                ]
            last_entry = last_entries[0] if last_entries and len(
                last_entries) > 0 else None

            document = Training.objects.get(resource_id=resource_id)

            logger.debug('Document recently modified : %s', resource_id)

            if document.title != title:
                logger.debug(
                    'Updating title of document {0}'.format(resource_id))
                document.title = title

            updated = calendar.timegm(updated.utctimetuple())
            document.last_updated = updated

            if last_entry:
                logger.debug('Previous entry found')
                logger.debug('Last entry : {0}'.format(last_entry))
                if last_entry['live'] is None:
                    logger.debug('Enabling live in DB for %s', resource_id)

                    document.is_live = True
                    document.is_displayed = True

                    email_task.apply_async([
                        'Document live',
                        Context({
                            'document_url':
                            GoogleDriveHelper.get_document_url(resource_id)
                        }), 'document_live', [a[1] for a in settings.ADMINS],
                        None, 'gmail'
                    ])
                else:
                    logger.debug('Document already live %s', resource_id)

                task_result['items'].append({
                    'document_id': resource_id,
                    'live': True
                })
            else:
                logger.debug('No previous entry found')
                logger.debug('Creating entry %s', resource_id)
                task_result['items'].append({
                    'document_id': resource_id,
                    'live': None
                })

            document.save()
        except Training.DoesNotExist:
            logger.debug('Unexisting resource {0}'.format(resource_id))
        except Exception:
            LoggingHelper.getErrorLogger().error(
                'An error occurred while detecting live', exc_info=1)

    logger.debug('Disabling documents not live anymore')
    Training.objects.filter(
        ~Q(resource_id__in=[item['file']['id'] for item in result['items']]),
        is_live=True).update(is_live=False)

    logger.debug('Result : %s', task_result)
    live_detection_change_feed.apply_async([task_result],
                                           eta=timezone.now() +
                                           timedelta(minutes=5))
    return task_result
예제 #7
0
파일: tasks.py 프로젝트: dylan-wu/unishared
def document_temp_share_task(document, user):
    logger.debug(
        u'Looking for a temporary share for training {0} and user {1}'.format(
            document.resource_id, user))

    trainingTempShares = TrainingTempShare.objects.filter(
        Q(user_invited=user) | Q(facebook_id=user.get_profile().facebook_id)
        | Q(email=user.email),
        training=document)

    if trainingTempShares.exists():
        logger.debug(
            u'Temporary share found for training {0} and user {1}'.format(
                document.resource_id, user))
        for trainingTempShare in trainingTempShares:
            if trainingTempShare.role == 'cowriters':
                if document.creator != user and user not in document.cowriters.all(
                ):
                    logger.debug(
                        u'Adding co-writer for training {0} and user {1}'.
                        format(document.resource_id, user))
                    document.cowriters.add(user)

                    if user in document.participants.all():
                        logger.debug(
                            u'Remove participant for training {0} and user {1}'
                            .format(document.resource_id, user))
                        document.participants.remove(user)
                    document.save()
                else:
                    logger.debug(
                        u'User {0} is already cowriter on training {1}'.format(
                            user, document.resource_id))
            elif trainingTempShare.role == 'participants':
                if document.creator != user and user not in document.participants.all(
                ) and user not in document.cowriters.all():
                    logger.debug(
                        u'Adding participant for training {0} and user {1}'.
                        format(document.resource_id, user))
                    document.participants.add(user)
                    document.save()
                else:
                    logger.debug(
                        u'User {0} is already cowriter/participant on training {1}'
                        .format(user, document.resource_id))
            trainingTempShare.delete()
    else:
        if document.creator != user and user not in document.cowriters.all(
        ) and user not in document.participants.all():
            logger.debug(
                'Adding participant for training {0} and user {1}'.format(
                    document.resource_id, user))
            document.participants.add(user)

            if Training.objects.filter(participants=user).count() == 1:
                logger.debug('Sending first participation mail')
                context = Context({
                    'user':
                    user,
                    'document': {
                        'url':
                        GoogleDriveHelper.get_document_url(
                            document.resource_id),
                        'title':
                        document.title
                    },
                    'ga_campaign_params':
                    'utm_source=unishared&utm_content=v1&utm_medium=e-mail&utm_campaign=new_document_participation_mail'
                })
                email_task.apply_async([
                    "Yihaa, you participated in a collaborative document!",
                    context, "new_document_participation_mail", [user.email]
                ])

        document.total_views += 1
        document.total_views_open25 += 1
        document.save()

        try:
            logger.debug(
                'Adding participation for training {0} and user {1}'.format(
                    document.resource_id, user))
            participation = TrainingParticipation.objects.get(
                user=user, training=document)
            participation.count += 1
            participation.save()
        except TrainingParticipation.DoesNotExist:
            TrainingParticipation.objects.create(user=user,
                                                 training=document,
                                                 count=1)