Exemplo n.º 1
0
def crop_image(image_id, coordinates, zoom, params):
    from ..models.company import Company
    image_query = db(File, id=image_id).one()  # get file object
    company_owner = db(Company).filter(or_(
                Company.system_folder_file_id == image_query.root_folder_id,
                Company.journalist_folder_file_id == image_query.root_folder_id)).one()  # get company file owner
    return File.crop(image_query, coordinates, zoom, company_owner, params)
Exemplo n.º 2
0
    def try_to_get_phrase(template, phrase, url, portal_id=None, allow_html=''):

        a_filter = dict(template=template, name=phrase, portal_id=portal_id)

        # TODO: OZ by OZ: this functions exists because we sometemes inmsert recort in flashing process (see on_value_changed decorator)
        # and we can`t use ORM
        def insert_record(**values):
            from profapp import utils
            g.db().execute(('INSERT INTO "%s" (template,   name,    portal_id, allow_html,   url,  %s) '
                            'VALUES           (:template, :name, :portal_id, :allow_html, :url,  :%s)') %
                           (TranslateTemplate.__tablename__, ', '.join(TranslateTemplate.languages),
                            ", :".join(TranslateTemplate.languages)),
                           params=utils.dict_merge(a_filter, {'allow_html': allow_html, 'url': url},
                                                   {l: phrase for l in TranslateTemplate.languages}, values))
            return db(TranslateTemplate, **a_filter).first()

        exist = db(TranslateTemplate, **a_filter).first()

        if portal_id and not exist:
            exist_for_another = db(TranslateTemplate, template=template, name=phrase,
                                   portal_id=TranslateTemplate.exemplary_portal_id).first()
            # TODO: OZ by OZ: how to select template portal? now we grab phrases from most recent portal, and there can be some unappropriate values
            if not exist_for_another:
                exist_for_another = db(TranslateTemplate, template=template, name=phrase).filter(
                    TranslateTemplate.portal != None).order_by(expression.asc(TranslateTemplate.cr_tm)).first()
            if exist_for_another:
                return insert_record(**{l: getattr(exist_for_another, l) for l in TranslateTemplate.languages})
        if not exist:
            return insert_record()

        return exist
Exemplo n.º 3
0
 def get_allowed_statuses(company_id=None, portal_id=None):
     if company_id:
         sub_query = db(MemberCompanyPortal, company_id=company_id).filter(
             MemberCompanyPortal.status != "DELETED").all()
     else:
         sub_query = db(MemberCompanyPortal, portal_id=portal_id)
     return sorted(list({partner.status for partner in sub_query}))
Exemplo n.º 4
0
def portal_banners_load(json, company_id):
    portal = Company.get(company_id).own_portal
    if 'action_name' in json:
        if json['action_name'] == 'create':
            place = db(PortalAdvertismentPlace, portal_layout_id=portal.portal_layout_id,
                       place=json['row']['place']).one()
            newrow = PortalAdvertisment(portal_id=portal.id, html=place.default_value if place.default_value else '',
                                        place=json['row']['place']).save()
            return {'grid_action': 'refresh_row', 'row': newrow.get_client_side_dict()}

        elif json['action_name'] == 'delete':
            PortalAdvertisment.get(json['id']).delete()
            return {'grid_action': 'delete_row'}
        elif json['action_name'] == 'set_default':
            adv = PortalAdvertisment.get(json['id'])
            place = db(PortalAdvertismentPlace, portal_layout_id=portal.portal_layout_id, place=adv.place).one()
            adv.html = place.default_value
            adv.save()
            return {}
    else:
        banners = PortalAdvertisment.get_portal_advertisments(portal)
        return {'page': 1,
                'grid_data': banners,
                'grid_filters': {},
                'total': len(banners)}
Exemplo n.º 5
0
 def __search_start(self, *args: dict, **kwargs):
     """ Don't use this method, use Search().search() method """
     subquery_search = self.__get_subquery(*args, ord_by=kwargs.get('order_by'))
     if self.__pagination:
         from ..controllers.pagination import pagination as pagination_func
         subquery_search, self.__pages, page, _ = pagination_func(subquery_search, page=self.__page,
                                                                  items_per_page=self.__items_per_page)
     subquery_search = subquery_search.subquery()
     join_search = []
     for arg in args:
         join_params = arg.get('join') or arg['class']
         join_search.append(db(subquery_search).join(join_params,
                                                     arg['class'].id == subquery_search.c.index).subquery())
     objects = collections.OrderedDict()
     to_order = {}
     _order_by = kwargs.get('order_by') or Search.ORDER_MD_TM
     ord_by = 'text' if type(_order_by) in (str, list, tuple) \
         else self.__order_by_to_str[_order_by]
     for search in join_search:
         for cls in db(search).all():
             objects[cls.index] = {'id': cls.index, 'table_name': cls.table_name,
                                   'order': getattr(cls, ord_by), 'md_tm': cls.md_tm}
             to_order[cls.index] = (getattr(cls, ord_by), getattr(cls, 'md_tm'))
     objects = {obj['id']: obj for obj in
                collections.OrderedDict(sorted(objects.items())).values()}
     ordered = sorted(tuple(to_order.items()), reverse=False if self.__desc_asc == 'asc' else True,
                      key=operator.itemgetter(1))
     self.__reload_func(len(ordered), *args)
     if self.__return_objects:
         objects = self.__get_objects_from_db(*args, ordered_objects_list=ordered)
     else:
         objects = collections.OrderedDict((id, objects[id]) for id, ord in ordered)
     return objects, self.__pages, self.__page
Exemplo n.º 6
0
 def subquery_search(filters=None, sorts=None, edit=None):
     sub_query = db(TranslateTemplate)
     list_filters = []
     list_sorts = []
     if edit:
         exist = db(TranslateTemplate, template=edit['template'], name=edit['name']).first()
         i = datetime.datetime.now()
         TranslateTemplate.get(exist.id).attr(
             {edit['col']: edit['newValue'], 'md_tm': i}).save().get_client_side_dict()
     if 'url' in filters:
         list_filters.append({'type': 'select', 'value': filters['url'], 'field': TranslateTemplate.url})
     if 'template' in filters:
         list_filters.append({'type': 'select', 'value': filters['template'], 'field': TranslateTemplate.template})
     if 'name' in filters:
         list_filters.append({'type': 'text', 'value': filters['name'], 'field': TranslateTemplate.name})
     if 'uk' in filters:
         list_filters.append({'type': 'text', 'value': filters['uk'], 'field': TranslateTemplate.uk})
     if 'en' in filters:
         list_filters.append({'type': 'text', 'value': filters['en'], 'field': TranslateTemplate.en})
     if 'portal.name' in filters:
         sub_query = sub_query.join(Portal,
                                    Portal.id == TranslateTemplate.portal_id)
         list_filters.append({'type': 'text', 'value': filters['portal.name'], 'field': Portal.name})
     if 'cr_tm' in sorts:
         list_sorts.append({'type': 'date', 'value': sorts['cr_tm'], 'field': TranslateTemplate.cr_tm})
     elif 'ac_tm' in sorts:
         list_sorts.append({'type': 'date', 'value': sorts['ac_tm'], 'field': TranslateTemplate.ac_tm})
     else:
         list_sorts.append({'type': 'date', 'value': 'desc', 'field': TranslateTemplate.cr_tm})
     sub_query = Grid.subquery_grid(sub_query, list_filters, list_sorts)
     return sub_query
Exemplo n.º 7
0
def search_for_company_to_join(json):
    companies, there_is_more = load_for_infinite_scroll(
        db(Company).filter(~db(UserCompany, user_id=g.user.id, company_id=Company.id).exists()). \
            filter(and_(
            Company.status == 'ACTIVE', Company.name.ilike("%" + json['text'] + "%")), ~Company.id.in_(json['loaded'])). \
            order_by(Company.name), items=3)

    return {'companies': [company.get_client_side_dict() for company in companies],
            'there_is_more': there_is_more}
Exemplo n.º 8
0
 def articles_visibility_for_user(portal_id):
     employer = True
     visibilities = Publication.VISIBILITIES.copy()
     if not db(UserCompany, user_id=getattr(g.user, 'id', None),
               status=UserCompany.STATUSES['ACTIVE']).filter(
                 UserCompany.company_id == db(Portal.company_owner_id, id=portal_id)).count():
         visibilities.pop(Publication.VISIBILITIES['CONFIDENTIAL'])
         employer = False
     return visibilities.keys(), employer
Exemplo n.º 9
0
def list_reader_from_front(portal_id):
    portal = Portal.get(portal_id)
    if g.user:
        portals = db(Portal).filter((Portal.id.in_(db(UserPortalReader.portal_id, user_id=g.user.id)))).all()
        if portal in portals:
            return redirect(url_for('index.list_reader'))
        else:
            return redirect(url_for('index.reader_subscribe', portal_id=portal_id))
    else:
        return redirect(url_for('index.auth_before_subscribe_to_portal', portal_id=portal_id))
Exemplo n.º 10
0
 def search_for_portal_to_join(company_id, searchtext):
     """This method return all portals which are not partners current company"""
     portals = []
     for portal in db(Portal).filter(Portal.name.ilike("%" + searchtext + "%")).all():
         member = db(MemberCompanyPortal, company_id=company_id, portal_id=portal.id).first()
         if member and member.status in Portal.ALLOWED_STATUSES_TO_JOIN:
             portals.append(portal.get_client_side_dict())
         elif not member:
             portals.append(portal.get_client_side_dict())
     return portals
Exemplo n.º 11
0
    def validate(self, is_new):
        ret = super().validate(is_new, regexps={
            'name': '[^\s]{2,}',
            'host': '^(([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]{1,})$'})
        errors = ret['errors']
        warnings = ret['warnings']

        if db(Portal, company_owner_id=self.own_company.id).filter(Portal.id != self.id).count():
            errors['form'] = 'portal for company already exists'

        if db(Portal, host=self.host).filter(Portal.id != self.id).count():
            errors['host'] = 'host already taken by another portal'

        import socket
        try:
            host = socket.gethostbyname(self.host)
            host_ip = str(host)
            if not 'host' in errors and 'host' in warnings and not host_ip in Config.OUR_IPS:
                warnings['host'] = 'Wrong Ip-address'
        except Exception as e:
            warnings['host'] = 'cannot resolve hostname. maybe unregistered'

        grouped_by_division_type = {}
        grouped_by_company_member = {}

        for inddiv, div in enumerate(self.divisions):
            if not re.match('[^\s]{3,}', div.name):
                utils.dict_deep_replace('pls enter valid name', errors, 'divisions', div.id, 'name')

            # number of division of some type
            utils.dict_deep_inc(grouped_by_division_type, div.portal_division_type.id)

            if div.portal_division_type.id == PortalDivision.TYPES['company_subportal']:
                utils.dict_deep_inc(grouped_by_company_member, div.settings['company_id'])

        for check_division_type in db(PortalDivisionType).all():
            utils.dict_deep_replace(0, grouped_by_division_type, check_division_type.id, if_not_exists=True)

            if check_division_type.min > grouped_by_division_type[check_division_type.id]:
                errors['add_division'] = 'you need at least %s `%s`' % (check_division_type.min, check_division_type.id)

            if check_division_type.max < grouped_by_division_type[check_division_type.id]:
                for inddiv, div in enumerate(self.divisions):
                    if div.portal_division_type.id == check_division_type.id:
                        utils.dict_deep_replace(
                            'you can have only %s `%s`' % (check_division_type.max, check_division_type.id),
                            errors, 'divisions', div.id, 'type')

        for inddiv, div in enumerate(self.divisions):
            if div.portal_division_type.id == PortalDivision.TYPES['company_subportal']:
                if grouped_by_company_member.get(div.settings['company_id'], 0) > 1:
                    utils.dict_deep_replace('you have more that one subportal for this company',
                                            warnings, 'divisions', div.id, 'settings')

        return ret
Exemplo n.º 12
0
 def apply_company_to_portal(company_id, portal_id):
     from ..models.company import Company
     """Add company to MemberCompanyPortal table. Company will be partner of this portal"""
     member = db(MemberCompanyPortal).filter_by(portal_id=portal_id, company_id=company_id).first()
     if member:
         member.set_client_side_dict(MemberCompanyPortal.STATUSES['APPLICANT'])
         member.save()
     else:
         g.db.add(MemberCompanyPortal(company=Company.get(company_id),
                                      portal=db(Portal, id=portal_id).one(),
                                      plan=db(MemberCompanyPortalPlan).first()))
         g.db.flush()
Exemplo n.º 13
0
    def apply_request(company_id, user_id, bool):
        """Method which define when employer apply or reject request from some user to
        subscribe to this company. If bool == True(Apply) - update rights to basic rights in company
        and status to active, If bool == False(Reject) - just update status to rejected."""
        if bool == 'True':
            stat = UserCompany.STATUSES['ACTIVE']
            UserCompany.update_rights(user_id, company_id, UserCompany.RIGHTS_AT_COMPANY_DEFAULT)
        else:
            stat = UserCompany.STATUSES['REJECTED']

        db(UserCompany, company_id=company_id, user_id=user_id,
           status=UserCompany.STATUSES['APPLICANT']).update({'status': stat})
Exemplo n.º 14
0
 def get_filter_for_portals_and_plans(portal_name=None, start_end_tm=None, package_name=None):
     filter_params = []
     if portal_name:
         filter_params.append(UserPortalReader.portal_id.in_(db(Portal.id).filter(
             Portal.name.ilike('%' + portal_name + '%'))))
     if start_end_tm:
         from_tm = datetime.datetime.utcfromtimestamp(int(start_end_tm['from'] + 1) / 1000)
         to_tm = datetime.datetime.utcfromtimestamp(int(start_end_tm['to'] + 86399999) / 1000)
         filter_params.extend([UserPortalReader.start_tm >= from_tm,
                               UserPortalReader.start_tm <= to_tm])
     if package_name:
         filter_params.append(UserPortalReader.portal_plan_id == db(ReaderUserPortalPlan.id).filter(
             ReaderUserPortalPlan.name.ilike('%' + package_name + '%')))
     return filter_params
Exemplo n.º 15
0
    def get_portals_and_plan_info_for_user(user_id, page, items_per_page, filter_params):
        from ..controllers.pagination import pagination
        query, pages, page, count = pagination(db(UserPortalReader, user_id=user_id).filter(filter_params),
                                               page=int(page), items_per_page=int(items_per_page))

        for upr in query:
            yield dict(id=upr.id, portal_id=upr.portal_id, status=upr.status, start_tm=upr.start_tm,
                       portal_logo=upr.portal.logo['url'],
                       end_tm=upr.end_tm if upr.end_tm > datetime.datetime.utcnow() else 'Expired at ' + upr.end_tm,
                       plan_id=upr.portal_plan_id,
                       plan_name=db(ReaderUserPortalPlan.name, id=upr.portal_plan_id).one()[0],
                       portal_name=upr.portal.name, portal_host=upr.portal.host, amount=upr.amount,
                       portal_divisions=[{division.name: division.id}
                                         for division in upr.portal.divisions])
Exemplo n.º 16
0
 def search_filter_default(self, division_id, company_id=None):
     """ :param division_id: string with id from table portal_division,
                optional company_id: string with id from table company. If provided
                , this function will check if ArticleCompany has relation with our class.
         :return: dict with prepared filter parameters for search method """
     division = db(PortalDivision, id=division_id).one()
     division_type = division.portal_division_type.id
     visibility = Publication.visibility.in_(Publication.articles_visibility_for_user(
         portal_id=division.portal_id)[0])
     filter = None
     if division_type == 'index':
         filter = {'class': Publication,
                   'filter': and_(Publication.portal_division_id.in_(db(
                       PortalDivision.id, portal_id=division.portal_id).filter(
                       PortalDivision.portal_division_type_id != 'events'
                   )), Publication.status == Publication.STATUSES['PUBLISHED'], visibility),
                   'return_fields': 'default_dict', 'tags': True}
     elif division_type == 'news':
         if not company_id:
             filter = {'class': Publication,
                       'filter': and_(Publication.portal_division_id == division_id,
                                      Publication.status ==
                                      Publication.STATUSES['PUBLISHED'], visibility),
                       'return_fields': 'default_dict', 'tags': True}
         else:
             filter = {'class': Publication,
                       'filter': and_(Publication.portal_division_id == division_id,
                                      Publication.status ==
                                      Publication.STATUSES['PUBLISHED'],
                                      db(ArticleCompany, company_id=company_id,
                                         id=Publication.article_company_id).exists(), visibility),
                       'return_fields': 'default_dict', 'tags': True}
     elif division_type == 'events':
         if not company_id:
             filter = {'class': Publication,
                       'filter': and_(Publication.portal_division_id == division_id,
                                      Publication.status ==
                                      Publication.STATUSES['PUBLISHED'], visibility),
                       'return_fields': 'default_dict', 'tags': True}
         else:
             filter = {'class': Publication,
                       'filter': and_(Publication.portal_division_id == division_id,
                                      Publication.status ==
                                      Publication.STATUSES['PUBLISHED'],
                                      db(ArticleCompany, company_id=company_id,
                                         id=Publication.article_company_id).exists(), visibility),
                       'return_fields': 'default_dict', 'tags': True}
     return filter
Exemplo n.º 17
0
    def get_portals_where_company_send_article(company_id):
        portals = {}

        for m in db(Material, company_id=company_id).all():
            for pub in m.publications:
                portals[pub.portal_division.portal.id] = pub.portal_division.portal.name
        return portals
Exemplo n.º 18
0
def edit_profile_submit(json, reader_portal_id):
    divisions_and_comments = db(UserPortalReader, id=reader_portal_id).one().show_divisions_and_comments
    for item in json['divisions']:
        for show_division_and_comments in divisions_and_comments:
            if item['division_id'] == show_division_and_comments.division_id:
                show_division_and_comments.show_divisions_and_comments = item['show_divisions_and_comments']
    return json
Exemplo n.º 19
0
 def subquery_portal_articles(portal_id, filters, sorts):
     sub_query = db(Publication)
     list_filters = []
     list_sorts = []
     if 'publication_status' in filters:
         list_filters.append(
             {'type': 'select', 'value': filters['publication_status'], 'field': Publication.status})
     if 'company' in filters:
         sub_query = sub_query.join(Publication.company)
         list_filters.append({'type': 'select', 'value': filters['company'], 'field': Company.id})
     if 'date' in filters:
         list_filters.append(
             {'type': 'date_range', 'value': filters['date'], 'field': Publication.publishing_tm})
     sub_query = sub_query. \
         join(Publication.portal_division). \
         join(PortalDivision.portal). \
         filter(Portal.id == portal_id)
     if 'title' in filters:
         list_filters.append({'type': 'text', 'value': filters['title'], 'field': Publication.title})
     if 'date' in sorts:
         list_sorts.append({'type': 'date', 'value': sorts['date'], 'field': Publication.publishing_tm})
     else:
         list_sorts.append({'type': 'date', 'value': 'desc', 'field': Publication.publishing_tm})
     sub_query = Grid.subquery_grid(sub_query, list_filters, list_sorts)
     return sub_query
Exemplo n.º 20
0
    def wrapper(*args, **kwargs):

        if g.debug or g.testing:
            if not func.__dict__.get('__check_rights__'):
                print('Please add "check_right" decorator for your func!')
            start = time.clock()
            try:
                ret = func(*args, **kwargs)
            except:
                import sys
                print("Unexpected error:", sys.exc_info()[0])
                return "Unexpected error:", sys.exc_info()[0]
                # return redirect(url_for('index.index'))
            end = time.clock()
            profiler = db(Profiler, name=func.__name__, blueprint_name=func.__dict__['__endpoint__']).first()
            method = ','.join([method for method in func.__dict__['__method__']]) if func.__dict__['__method__'] else None
            if profiler:
                profiler.update_profile(end-start, method)
            else:
                Profiler().create_profile(func.__name__, func.__dict__['__endpoint__'], end-start, method)
            return ret
        else:
            if not func.__dict__['__check_rights__']:
                raise Exception('method not allowed! Please add "check_right" decorator for your func!')
            try:
                ret = func(*args, **kwargs)
            except:
                import sys
                print("Unexpected error:", sys.exc_info()[0])
                return "Unexpected error:", sys.exc_info()[0]
        return ret
Exemplo n.º 21
0
def config_load(json):
    page = json.get('paginationOptions')['pageNumber']
    pageSize = json.get('paginationOptions')['pageSize']
    params = {}
    params['sort'] = {}
    params['filter'] = {}
    params['search_text'] = {}
    if json.get('sort'):
        for n in json.get('sort'):
            params['sort'][n] = json.get('sort')[n]
    if json.get('filter'):
        for b in json.get('filter'):
            if json.get('filter')[b] != '-- all --':
                params['filter'][b] = json.get('filter')[b]
    if json.get('search_text'):
        for d in json.get('search_text'):
            params['search_text'][d] = json.get('search_text')[d]
    if json.get('editItem'):
        exist = db(Config, template=json.get('editItem')['template'], name=json.get('editItem')['name']).first()
        i = datetime.datetime.now()
        Config.get(exist.id).attr({json.get('editItem')['col']: json.get('editItem')['newValue'], 'md_tm':i}).save().get_client_side_dict()
    subquery = Config.subquery_search(template=json.get('template') or None,
                                                 url=json.get('url') or None,
                                                 **params)

    translations, pages, current_page, count = pagination(subquery, page=page, items_per_page=pageSize)
    grid_data = TranslateTemplate.getListGridDataTranslation(translations)

    return {'grid_data': grid_data,
            'total': subquery.count()
            }
Exemplo n.º 22
0
def get_company_member_and_division(portal: Portal, company_id, company_name):
    # TODO: OZ by OZ: redirect if name is wrong
    portal_dict = portal_and_settings(portal)
    # TODO: OZ by OZ: heck company is member
    member_company = Company.get(company_id)
    membership = db(MemberCompanyPortal, company_id=member_company.id, portal_id=portal.id).one()
    di = None
    for d_id, d in portal_dict['divisions'].items():
        if 'subportal_company' in d and d['subportal_company'].id == company_id:
            di = g.db().query(PortalDivisionSettingsCompanySubportal). \
                join(MemberCompanyPortal,
                     MemberCompanyPortal.id == PortalDivisionSettingsCompanySubportal.member_company_portal_id). \
                join(PortalDivision,
                     PortalDivision.id == PortalDivisionSettingsCompanySubportal.portal_division_id). \
                filter(MemberCompanyPortal.company_id == member_company.id). \
                filter(PortalDivision.portal_id == portal.id).one().portal_division

    if not di:
        # TODO: YG: by OZ: change all hardcoded portal_division_types_id (like '<here some index>') to PortalDivision.TYPES[<here some index>]
        di = g.db().query(PortalDivision).filter_by(portal_id=portal.id,
                                                    portal_division_type_id=PortalDivision.TYPES[
                                                        'catalog']).first()
    if not di:
        di = g.db().query(PortalDivision).filter_by(portal_id=portal.id,
                                                    portal_division_type_id=PortalDivision.TYPES[
                                                        'index']).one()
    return membership, member_company, di
Exemplo n.º 23
0
    def validate(self, is_new):

        ret = super().validate(is_new)
        if not re.match(r'[^\s]{2}', self.first_name):
            ret['errors']['first_name'] = 'Your First name must be at least 2 characters long.'
        if not re.match(r'[^\s]{2}', self.last_name):
            ret['errors']['last_name'] = 'Your Last name must be at least 2 characters long.'

        if not re.match(REGEXP.EMAIL, self.address_email):
            ret['errors']['email'] = 'Please enter correct email'
        elif is_new and db(User, address_email=self.address_email).first():
            ret['errors']['email'] = 'Sorry. this email is taken'

        if is_new and (self.password is None or self.password == ''):
            ret['errors']['password'] = '******'

        if self.password is not None:
            if self.check_password_strength() < 30:
                ret['errors']['password'] = '******'
            elif self.check_password_strength() < 50:
                ret['warnings']['password'] = '******'

        if self.password is not None and self.password != self.password_confirmation:
            ret['errors']['password_confirmation'] = 'Password and confirmation does not match'

        return ret
Exemplo n.º 24
0
def get_portal_dict_for_material(portal, company, material=None, publication=None, submit=None):
    ret = {}
    ret['portal'] = portal.get_client_side_dict(
        fields='id, name, host, logo.url, divisions.id|name|portal_division_type_id, own_company.name|id, own_company.logo.url')

    
    ret['divisions'] = PRBase.get_ordered_dict([d for d in ret['portal']['divisions'] if (
        d['portal_division_type_id'] == 'events' or d['portal_division_type_id'] == 'news')])
    ret['company_id'] = company.id
    if material:
        publication_in_portal = db(Publication).filter_by(material_id=material.id).filter(
            Publication.portal_division_id.in_(
                [div_id for div_id, div in ret['divisions'].items()])).first()
    else:
        publication_in_portal = publication
    if publication_in_portal:
        if submit:
            ret['replace_id'] = publication_in_portal.id
        ret['id'] = portal.id if submit else publication_in_portal.id
        ret['publication'] = publication_in_portal.get_client_side_dict(
            'id,status,visibility,portal_division_id,publishing_tm')
        ret['publication']['portal_division'] = ret['divisions'][ret['publication']['portal_division_id']]
        ret['publication']['counts'] = '0/0/0/0'
        ret['actions'] = PublishUnpublishInPortal(publication=publication_in_portal,
                                                  division=publication_in_portal.portal_division, company=company).actions()

    else:
        ret['id'] = portal.id
        ret['publication'] = None
        ret['actions'] = {EditOrSubmitMaterialInPortal.ACTIONS['SUBMIT']:
                              EditOrSubmitMaterialInPortal(material=material, portal=portal).actions()[
                                  EditOrSubmitMaterialInPortal.ACTIONS['SUBMIT']]}

    return ret
Exemplo n.º 25
0
def send(parent_id):
    parent = File.get(parent_id)
    root = parent.root_folder_id
    if parent.mime == 'root':
        root = parent.id
    company = db(Company, journalist_folder_file_id=root).one()
    if FilemanagerRights(company=company).action_is_allowed(FilemanagerRights.ACTIONS['UPLOAD']) != True:
        return jsonify({'error': True})
    data = request.form
    uploaded_file = request.files['file']
    name = File.get_unique_name(urllib.parse.unquote(uploaded_file.filename).replace(
        '"', '_').replace('*', '_').replace('/', '_').replace('\\', '_'), data.get('ftype'), parent.id)
    data.get('ftype')
    if re.match('^video/.*', data.get('ftype')):
        body = {'title': uploaded_file.filename,
                'description': '',
                'status': 'public'}
        youtube = YoutubeApi(body_dict=body,
                             video_file=uploaded_file.stream.read(-1),
                             chunk_info=dict(chunk_size=int(data.get('chunkSize')),
                                             chunk_number=int(data.get('chunkNumber')),
                                             total_size=int(data.get('totalSize'))),
                             company_id=company.id,
                             root_folder_id=company.journalist_folder_file_id,
                             parent_folder_id=parent_id)
        file = youtube.upload()
    else:
        file = File.upload(name, data, parent.id, root, company, content=uploaded_file.stream.read(-1))
    return jsonify({'result': {'size': 0}, 'error': True if file == 'error' else False, 'file_id': file})
Exemplo n.º 26
0
    def __get_subquery(self, *args, ord_by=None):
        def add_joined_search(field_name):
            joined = db(Search.index, func.min(Search.text).label('text'),
                        func.min(Search.table_name).label('table_name'),
                        index=subquery_search.subquery().c.index).filter(
                Search.kind.in_(tuple(field_name))).group_by(Search.index)
            return joined

        subquery_search = db(Search.index.label('index'),
                             func.sum(Search.relevance).label('relevance'),
                             func.min(Search.table_name).label('table_name'),
                             func.min(Search.md_tm).label('md_tm'),
                             func.max(Search.position).label('position'),
                             func.max(Search.text).label('text')).filter(
            or_(*self.__get_search_params(*args))).group_by('index')
        if type(ord_by) in (str, list, tuple):
            order = self.__get_order('text', 'text')
            subquery_search = add_joined_search(ord_by)
        elif type(ord_by) == int:
            ord_to_str = self.__order_by_to_str[ord_by]
            order = self.__get_order(ord_to_str, ord_to_str)
        else:
            order = self.__get_order('relevance', 'relevance')
        if 'md_tm' in str(order):
            subquery_search = subquery_search.order_by(order)
        else:
            subquery_search = subquery_search.order_by(order).order_by(
                self.__get_order('md_tm', 'md_tm'))
        return subquery_search
Exemplo n.º 27
0
def remove(json, file_id):
    file = File.get(file_id)
    ancestors = File.ancestors(file.parent_id)
    if not file or FilemanagerRights(
            company=db(Company, journalist_folder_file_id=ancestors[0]).first()).action_is_allowed(
        FilemanagerRights.ACTIONS['REMOVE'], file) != True:
        return False
    return file.remove()
Exemplo n.º 28
0
    def get_related_articles(self, count=5):
        from sqlalchemy.sql import func

        return g.db().query(Publication).filter(
            and_(Publication.id != self.id,
                 Publication.portal_division_id.in_(
                     db(PortalDivision.id).filter(PortalDivision.portal_id == self.portal_division.portal_id))
                 )).order_by(func.random()).limit(count).all()
Exemplo n.º 29
0
def employment_change_position(json, company_id, employment_id):
    employment = db(UserCompany).filter_by(id=employment_id).one()

    employment.position = json['position']
    employment.save()

    return utils.dict_merge(employment.get_client_side_dict(),
                            {'actions': EmployeesRight(company=company_id, employment=employment).actions()})
Exemplo n.º 30
0
 def set_tags_positions(self):
     tag_position = 0
     for tag in self.tags:
         tag_position += 1
         tag_pub = db(TagMembership).filter(and_(TagMembership.tag_id == tag.id,
                                                 TagMembership.member_company_portal_id == self.id)).one()
         tag_pub.position = tag_position
         tag_pub.save()
     return self