1# Copyright (c) 2012-2016 Seafile Ltd.
2# -*- coding: utf-8 -*-
3import logging
4
5from django.db import IntegrityError
6from django.db.models import Q
7
8from seahub.base.models import UserStarredFiles
9from seahub.utils import normalize_file_path, normalize_dir_path
10
11# Get an instance of a logger
12logger = logging.getLogger(__name__)
13
14def star_file(email, repo_id, path, is_dir, org_id=-1):
15    if is_file_starred(email, repo_id, path, org_id):
16        return
17
18    f = UserStarredFiles(email=email,
19                         org_id=org_id,
20                         repo_id=repo_id,
21                         path=path,
22                         is_dir=is_dir)
23    try:
24        f.save()
25    except IntegrityError as e:
26        logger.warn(e)
27
28def unstar_file(email, repo_id, path):
29    # Should use "get", but here we use "filter" to fix the bug caused by no
30    # unique constraint in the table
31    result = UserStarredFiles.objects.filter(email=email,
32                                             repo_id=repo_id,
33                                             path=path)
34    for r in result:
35        r.delete()
36
37def is_file_starred(email, repo_id, path, org_id=-1):
38    # Should use "get", but here we use "filter" to fix the bug caused by no
39    # unique constraint in the table
40
41    path_list = [normalize_file_path(path), normalize_dir_path(path)]
42    result = UserStarredFiles.objects.filter(email=email,
43            repo_id=repo_id).filter(Q(path__in=path_list))
44
45    n = len(result)
46    if n == 0:
47        return False
48    else:
49        # Fix the bug caused by no unique constraint in the table
50        if n > 1:
51            for r in result[1:]:
52                r.delete()
53        return True
54
55def get_dir_starred_files(email, repo_id, parent_dir, org_id=-1):
56    '''Get starred files under parent_dir.
57
58    '''
59    starred_files = UserStarredFiles.objects.filter(email=email,
60                                         repo_id=repo_id,
61                                         path__startswith=parent_dir,
62                                         org_id=org_id)
63    return [ normalize_file_path(f.path) for f in starred_files ]
64
65