1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-04-27 11:01:14 +00:00
seahub/seahub/api2/endpoints/utils.py
sniper-py 99a9ece04e Python3 master (#4076)
* delete thridpart/social_django

* delete social_django in seahub/urls.py

* delete social_django in seahub/settings.py

* delete seahub/notifications/management/commands/send_wxwork_notices.py

* delete social_django in code annotation

* delete seahub/social_core

* delete tests/seahub/social_core

* delete social_core in seahub/urls.py

* delete social_core in seahub/settings.py

* change app_label to auth in SocialAuthUser model

* 2to3 asserts

* 2to3 basestring

* 2to3 dict

* 2to3 except

* 2to3 filter

* 2to3 future

* 2to3 has_key

* 2to3 idioms

* 2to3 import

* 2to3 imports

* 2to3 long

* 2to3 map

* 2to3 next

* 2to3 numliterals

* 2to3 print

* 2to3 raise

* 2to3 raw_input

* 2to3 reduce

* 2to3 reload

* 2to3 set_literal

* 2to3 unicode

* 2to3 urllib

* 2to3 ws_comma

* 2to3 xrange

* 2to3 zip

* add pymysql in __init__.py

* fix encode and decode in seahub/cconvert.py

* fix seafserv_rpc.is_passwd_set in seahub/views/__init__.py

* fix smart_unicode to smart_text

* fix force_unicode to force_text

* delete seaserv.get_session_info

* delete seaserv.ccnet_rpc

* fix indent error in seahub/auth/middleware.py

* update dev-requirements

* update test-requirements

* update requirements

* fix StringIO to BytesIO in thumbnail

* fix seaserv.list_inner_pub_repos to seafile_api.get_inner_pub_repo_list

* fix seaserv.list_org_inner_pub_repos to seafile_api.list_org_inner_pub_repos

* add logger in seahub/utils/__init__.py

* fix sort cmp in seahub/views/__init__.py

* fix sort cmp in seahub/base/management/commands/export_file_access_log.py

* fix sort cmp in seahub/api2/endpoints/repo_trash.py

* fix sort cmp in seahub/api2/endpoints/shared_repos.py

* fix sort cmp in seahub/api2/endpoints/shared_folders.py

* fix sort cmp in seahub/wiki/views.py

* fix sort cmp in seahub/api2/endpoints/wiki_pages.py

* fix sort cmp in seahub/api2/endpoints/group_libraries.py

* fix sort cmp in seahub/base/models.py

* fix sort cmp in seahub/api2/endpoints/upload_links.py

* fix sort cmp in seahub/views/ajax.py

* fix sort cmp in seahub/api2/views.py

* fix sort cmp in seahub/views/wiki.py

* fix sort cmp in seahub/api2/endpoints/repos.py

* fix sort cmp in seahub/api2/endpoints/starred_items.py

* fix sort cmp in seahub/views/file.py

* fix sort cmp in seahub/api2/endpoints/dir.py

* fix sort cmp in seahub/api2/endpoints/share_links.py

* fix cmp to cmp_to_key in seahub/api2/endpoints/admin/device_trusted_ip.py

* fix cmp to cmp_to_key in tests/api/endpoints/admin/test_device_trusted_ip.py

* delete encode('utf-8') in seafile_api.list_dir_by_commit_and_path

* delete encode('utf-8') in is_file_starred

* delete encode('utf-8') in seafile_api.list_dir_by_path

* delete path.encode('utf-8') in seahub/views/file.py

* fix os.write to add encode('utf-8')

* add encode('utf-8') for hashlib

* add encode('utf-8') for hmac

* fix with open(file, 'wb') for binary file

* fix encode and decode in seahub/utils/hasher.py

* fix next in thirdpart/shibboleth/views.py

* fix next in seahub/profile/views.py

* fix next in seahub/notifications/views.py

* fix next in seahub/institutions/views.py

* fix next in seahub/options/views.py

* fix next in seahub/share/views.py

* fix next in seahub/avatar/views.py

* fix next in seahub/views/__init__.py

* fix next in seahub/group/views.py

* fix next in seahub/views/wiki.py

* fix next in seahub/views/sysadmin.py

* fix next in seahub/views/file.py

* fix string.lowercase to string.ascii_lowercase in test

* fix open file add 'rb' in test

* fix self.user.username in test

* add migrations in file_participants

* fix list_org_inner_pub_repos to list_org_inner_pub_repos_by_owner

* fix from seaserv import is_passwd_set to seafile_api.is_password_set

* fix assert bytes resp.content in test

* fix seafile_api.get_inner_pub_repo_list to seafile_api.list_inner_pub_repos_by_owner

* fix seafile_api.is_passwd_set to seafile_api.is_password_set

* fix AccountsApiTest assert length

* rewrite sort_devices cmp to operator.lt

* fix bytes + str in seahub/api2/views.py

* fix assert bytes resp.content in test

* fix hashlib encode in seahub/thirdpart/registration/models.py

* change app_label to base in SocialAuthUser

* fix base64 encode in seahub/base/database_storage/database_storage.py

* fix assert bytes resp.content

* remove path.decode in def mkstemp()

* remove path.decode in FpathToLinkTest

* remove str decode in FileTagTest

* remove mock_write_xls.assert_called_once() in SysUserAdminExportExcelTest

* fix urllib assert in FilesApiTest

* fix link fields in FileCommentsTest

* fix get_related_users_by_repo()

* fix assert list in GetRepoSharedUsersTest

* fix create user in AccountTest

* fix repeated key in dict seahub/api2/views.py

* add drone.yml

* update nginx conf in test

* update test conf in test

* update dist and push after test success

* update drone conf to dist and push

* fix assert in BeSharedReposTest

* fix seafile_api.list_org_inner_pub_repos_by_owner(org_id, username) to seafile_api.list_org_inner_pub_repos(org_id)

* fix seafile_api.list_inner_pub_repos_by_owner(username) to seafile_api.get_inner_pub_repo_list()

* update pyjwt requirement

* update dist branch in drone

* add SKIP in dist and push

* fix StringIO to BytesIO in seahub/avatar/models.py

* fix if org_id > 0 to if org_id and org_id > 0

* remove payment

* fix StringIO to BytesIO in seahub/base/database_storage/database_storage.py

* fix send_message to seafile_api.publish_event in seahub/drafts/utils.py

* fix send_message to seafile_api.publish_event in seahub/api2/views.py

* fix send_message to seafile_api.publish_event in seahub/api2/endpoints/repos.py

* fix send_message to seafile_api.publish_event in seahub/views/file.py

* fix send_message to seafile_api.publish_event in seahub/utils/__init__.py

* fix image_file.read encode in seahub/base/database_storage/database_storage.py

* fix DatabaseStorageTest

* remove .travis.yml

* drone branch include master
2019-09-11 11:46:43 +08:00

192 lines
5.9 KiB
Python

# Copyright (c) 2012-2016 Seafile Ltd.
import re
import datetime
import time
import urllib.request, urllib.parse, urllib.error
import logging
from rest_framework import status
from seaserv import ccnet_api, seafile_api
from pysearpc import SearpcError
from seahub.api2.utils import api_error
from seahub.base.templatetags.seahub_tags import email2nickname, \
email2contact_email
from seahub.utils import get_log_events_by_time, is_pro_version, is_org_context
try:
from seahub.settings import MULTI_TENANCY
except ImportError:
MULTI_TENANCY = False
logger = logging.getLogger(__name__)
def api_check_group(func):
"""
Decorator for check if group valid
"""
def _decorated(view, request, group_id, *args, **kwargs):
group_id = int(group_id) # Checked by URL Conf
try:
group = ccnet_api.get_group(int(group_id))
except SearpcError as e:
logger.error(e)
error_msg = 'Internal Server Error'
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
if not group:
error_msg = 'Group %d not found.' % group_id
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
return func(view, request, group_id, *args, **kwargs)
return _decorated
def add_org_context(func):
def _decorated(view, request, *args, **kwargs):
if is_org_context(request):
org_id = request.user.org.org_id
else:
org_id = None
return func(view, request, org_id=org_id, *args, **kwargs)
return _decorated
def is_org_user(username, org_id=None):
""" Check if an user is an org user.
Keyword arguments:
org_id -- An integer greater than zero. If provided,
check if the user is a member of the specific org.
"""
if not is_pro_version() or not MULTI_TENANCY:
return False
try:
if org_id:
# Return non-zero if True, otherwise 0.
return ccnet_api.org_user_exists(org_id, username) != 0
else:
orgs = ccnet_api.get_orgs_by_user(username)
return len(orgs) > 0
except Exception as e:
logger.error(e)
return False
def get_user_contact_email_dict(email_list):
email_list = set(email_list)
user_contact_email_dict = {}
for email in email_list:
if email not in user_contact_email_dict:
user_contact_email_dict[email] = email2contact_email(email)
return user_contact_email_dict
def get_user_name_dict(email_list):
email_list = set(email_list)
user_name_dict = {}
for email in email_list:
if email not in user_name_dict:
user_name_dict[email] = email2nickname(email)
return user_name_dict
def get_repo_dict(repo_id_list):
repo_id_list = set(repo_id_list)
repo_dict = {}
for repo_id in repo_id_list:
if repo_id not in repo_dict:
repo_dict[repo_id] = ''
repo = seafile_api.get_repo(repo_id)
if repo:
repo_dict[repo_id] = repo
return repo_dict
def get_group_dict(group_id_list):
group_id_list = set(group_id_list)
group_dict = {}
for group_id in group_id_list:
if group_id not in group_dict:
group_dict[group_id] = ''
group = ccnet_api.get_group(int(group_id))
print(group)
if group:
group_dict[group_id] = group
return group_dict
def check_time_period_valid(start, end):
if not start or not end:
return False
# check the date format, should be like '2015-10-10'
date_re = re.compile(r'^(\d{4})\-([1-9]|0[1-9]|1[012])\-([1-9]|0[1-9]|[12]\d|3[01])$')
if not date_re.match(start) or not date_re.match(end):
return False
return True
def get_log_events_by_type_and_time(log_type, start, end):
start_struct_time = datetime.datetime.strptime(start, "%Y-%m-%d")
start_timestamp = time.mktime(start_struct_time.timetuple())
end_struct_time = datetime.datetime.strptime(end, "%Y-%m-%d")
end_timestamp = time.mktime(end_struct_time.timetuple())
end_timestamp += 24 * 60 * 60
events = get_log_events_by_time(log_type, start_timestamp, end_timestamp)
events = events if events else []
return events
def generate_links_header_for_paginator(base_url, page, per_page, total_count, option_dict={}):
def is_first_page(page):
return True if page == 1 else False
def is_last_page(page, per_page, total_count):
if page * per_page >= total_count:
return True
else:
return False
if not isinstance(option_dict, dict):
return ''
query_dict = {'page': 1, 'per_page': per_page}
query_dict.update(option_dict)
# generate first page url
first_page_url = base_url + '?' + urllib.parse.urlencode(query_dict)
# generate last page url
last_page_query_dict = {'page': (total_count / per_page) + 1}
query_dict.update(last_page_query_dict)
last_page_url = base_url + '?' + urllib.parse.urlencode(query_dict)
# generate next page url
next_page_query_dict = {'page': page + 1}
query_dict.update(next_page_query_dict)
next_page_url = base_url + '?' + urllib.parse.urlencode(query_dict)
# generate prev page url
prev_page_query_dict = {'page': page - 1}
query_dict.update(prev_page_query_dict)
prev_page_url = base_url + '?' + urllib.parse.urlencode(query_dict)
# generate `Links` header
links_header = ''
if is_first_page(page):
links_header = '<%s>; rel="next", <%s>; rel="last"' % (next_page_url, last_page_url)
elif is_last_page(page, per_page, total_count):
links_header = '<%s>; rel="first", <%s>; rel="prev"' % (first_page_url, prev_page_url)
else:
links_header = '<%s>; rel="next", <%s>; rel="last", <%s>; rel="first", <%s>; rel="prev"' % \
(next_page_url, last_page_url, first_page_url, prev_page_url)
return links_header