Exemple #1
0
def upload(request, uri):
    if request.POST:
        _uri = request.POST.get("uri")
        _md5_hash = request.POST.get("hash")
        _name = request.POST.get("name")
        _description = request.POST.get("description")
        _time = datetime.datetime.now()
        _directory = request.POST.get("directory")
        if _directory != "":
            _rank = 2
            # 判断文件夹是否存在,若存在,则其中文件数加一,否则创建新的文件夹
            try:
                d = Directory.objects.get(uri=uri + "/" + _directory)
            except Directory.DoesNotExist:
                d = None
            if d:
                d.file_num += 1
                d.save()
            else:
                d = Directory(uri=uri + "/" + _directory, file_num=1, time=_time, name=_directory)
                d.save()
        else:
            _rank = 1
        pd = PrimaryDirectory.objects.get(uri=uri)
        pd.file_num += 1
        pd.save()
        file = File(uri=_uri, md5_hash=_md5_hash, name=_name,
                    description=_description, time=_time,
                    url=getDownloadUrl(_uri), download_num=0, rank=_rank)
        file.save()
        return HttpResponse("ok")
    return render_to_response("upload.html", {"uri": uri}, context_instance=RequestContext(request))
 def get_contents(self):
     db_id = Directory.get(Directory.key == self.key).id
     directories = Directory.select().where(Directory.parent_directory == db_id)
     has_probes = False
     try:
         has_probes = Directory.get(Directory.key == directories
                             .first().key).images.first()
     except:
         pass
     if has_probes:
         directories = [DirectoryTree(d.name, d.key).get_contents() for d in directories]
         self.directories = [d.serialized for d in directories]
     else:
         self.directories = [DirectoryTree(d.name, d.key).serialized for d in directories]
     self.images = [image.serialized for image in Image.select().where(Image.directory == db_id)]
     if self.images:
         stack_title = self.key[:-1]
         try:
             stack_id = Stack.get(Stack.title == stack_title).id
         except models.DoesNotExist:
             images = Image.select().where(Image.directory == db_id)
             stack = models.Stack.create(title=stack_title)
             for image in images:
                 try:
                     models.StackImage.create(stack=stack, image = image.id)
                 except Exception as ex:
                     print ex
             stack_id = stack.id
         self.stack_id = stack_id
     return self
def transfer_s3_structure_to_db(name, path, parent_directory, is_dir=False):
    if parent_directory is not None:
        par_dir = Directory.get(Directory.key == parent_directory)
    else:
        par_dir = FakeDirectory()
        par_dir.id = None
    if is_dir:
        try:
            Directory.get(Directory.key == path)
            return False
        except DoesNotExist:
            Directory.create(
                name = name,
                key = path,
                parent_directory = par_dir.id
            )
            return True
    else:
        try:
            Image.get(Image.key == path)
            return False
        except DoesNotExist:
            Image.create(
                name = name,
                key = path,
                directory = par_dir.id
            )
            return True
Exemple #4
0
 def parent_exists(self):
   """
   Проверка существования родительской директории
   """
   parent, name = self.split_parent_dir()
   return ('/' not in parent) or (
       Directory.gql('WHERE path = :1', self.split_parent_dir()[0]).count() > 0)
Exemple #5
0
def post_directory(request):

    data = json.loads(request.body)

    if all (key in data for key in ("name", "parent")):

        name = data['name']
        parent = Directory.objects.get(id=data['parent']) if type(data['parent']) is int else None; 

        directory = Directory(name=name, parent=parent, owner=request.user, bytes=0)
        
        directory.save()

        return JsonResponse(directory.get_client_inode(), safe=False)

    return JsonResponse({'message':'Invalid post data..'}, status=400, safe=False)
Exemple #6
0
    def _addDirectory(self):
        '''
        Add directory to settings
        '''
        panel = NSOpenPanel.openPanel()
        panel.setCanChooseFiles_(False)
        panel.setCanChooseDirectories_(True)
        panel.setAllowsMultipleSelection_(True)
        if panel.runModal() == NSModalResponseOK:
            for url in panel.URLs():
                pred = NSPredicate.predicateWithFormat_(
                    "path == %@", url.path())
                if self.data['paths'].filteredArrayUsingPredicate_(
                        pred).count() > 0:
                    continue

                directory = Directory.alloc().init()
                directory.path = url.path()
                directory.enable = True
                directory.depth = 1

                self.tableView.beginUpdates()
                self.data['paths'].addObject_(directory)
                index = NSIndexSet.indexSetWithIndex_(
                    self.data['paths'].count() - 1)
                self.tableView.insertRowsAtIndexes_withAnimation_(
                    index, NSTableViewAnimationSlideUp)
                self.tableView.endUpdates()

                # Save to file
                self.saveSettings()
def build_directory_tree(root_directory_key, root_directory_name):
    directory_db_model = Directory.get(Directory.key == root_directory_key)
    root_directory = DirectoryTree(root_directory_name, root_directory_key)
    root_directory = get_directory_contents(root_directory)
    root_directory.directories = [build_directory_tree(directory.key, directory.name) 
                                 for directory in root_directory.directories]
    # images = Image.select().where(Image.directory.key == directory_db_model.key)
    images = directory_db_model.images
    root_directory.images = [image.serialized for image in images]
    return root_directory
Exemple #8
0
def addDir(dir_id):
    name = request.form.get('name')
    parent_dir = Directory.query.filter_by(id=dir_id).one()
    path = os.path.join(parent_dir.path, parent_dir.name)
    newDir = Directory(dir_id, name, path)
    db.session.add(newDir)
    db.session.commit()
    os.mkdir(os.path.join(STORAGE, path, name), 511)
    return json.dumps({'success': True}), 200, {
        'ContentType': 'application/json'
    }
    def walk(self, path, include_files=True):
        """
		Walk 'path' and map the directories into the main vTree
		"""
        # add the last directory in the 'path' as our top level
        # directory in the vTree
        base_path = os.path.dirname(path)
        root_dir = os.path.basename(path)
        os.chdir(base_path)
        if os.path.isdir(root_dir):
            self.dirs.append(Directory(path=root_dir))
        else:
            print "Error: Could not find %s" % path
            return
        for root, dirs, files in os.walk(root_dir):
            for directory in dirs:
                self.dirs.append(Directory(path="%s/%s" % (root, directory)))
            if include_files:
                for fl in files:
                    self.files.append(File(path="%s/%s" % (root, fl)))
  def dir_exists(self):
    """
    Проверка существования рабочей директории
    """
    path, name = split_url(self.file_url())

    parts = path.split('/')
    dirname = parts.pop()
    dirpath = '/'.join(parts)

    dir = Directory.gql('WHERE path = :path AND name = :name', path=dirpath, name=dirname)
    return dir.count() != 0
Exemple #11
0
 def post(self):
   """
   Создание новой директории внутри существующей директории
   """
   if self.dir_exists():
     self.error(400, 'Directory already exists')
   else:
     if self.parent_exists():
       parent, name = self.split_parent_dir()
       Directory(path=parent, name=name).put()
     else:
       self.error(404, 'Parent directory doesn\'t exist')
Exemple #12
0
    def delete_data(self, parent_key, sub_key, clear_from_db=True):
        """
        Used to delete record from db if clear_from_db=True, also
        clens up from cache.
        """

        num_records = 0

        if clear_from_db:
            num_records = Directory.objects(id=sub_key).delete()

        key = "%s__%s" % (parent_key, sub_key)
        self.delete(key)
        return num_records
    def dir_exists(self):
        """
    Проверка существования рабочей директории
    """
        path, name = split_url(self.file_url())

        parts = path.split('/')
        dirname = parts.pop()
        dirpath = '/'.join(parts)

        dir = Directory.gql('WHERE path = :path AND name = :name',
                            path=dirpath,
                            name=dirname)
        return dir.count() != 0
    def load(department, tree_type, version=None, name=None, verbose=False):
        """
		Load a vTree from the db
		"""
        tree = vTree.find(department=department,
                          tree_type=tree_type,
                          name=name,
                          version=version,
                          limit='last')
        if not tree: return None
        tree = tree[0]
        if verbose:
            print "\nLoaded vTree:"
            print "  %-12s %s" % ('Name:', tree.data['name'])
            print "  %-12s %s" % ('Department:', tree.data['department'])
            print "  %-12s %s" % ('Tree Type:', tree.data['tree_type'])
            print "  %-12s %s\n" % ('Version:', tree.data['version'])
        tree.dirs = Directory.find(vTree_uid=tree.data['uid'])
        tree.files = File.find(vTree_uid=tree.data['uid'])
        return tree
Exemple #15
0
def suggest():
	form = suggestForm(request.form)
	if form.validate():
		title = form.title.data
		url = form.url.data
		desc = form.description.data
		email = form.email.data
		cat = form.category.data

		new_dir = Directory(url, title, desc, cat)
		db.session.add(new_dir)
		db.session.commit()

		return redirect(url_for('index'))


	else:
		print 'wrong input'

	return render_template('suggest.html', form=form)
Exemple #16
0
def check(current_user_key, cwd_id):

    owner = MyUser.get(cwd_id.split('/')[0])
    if owner:

        directory = Directory.get_by_id(cwd_id, owner.key)
        if directory:

            parent = None

            is_shared = directory.is_users_dir(current_user_key)
            if not is_shared:
                parent = directory

                while parent and not is_shared and current_user_key not in parent.lock:
                    is_shared = parent.is_shared_to_me(current_user_key)
                    if not is_shared:
                        parent = parent.get_parent()

            if is_shared:
                return owner, directory, parent

    return None, None, None
Exemple #17
0
 def load(cls):
     '''
     Load the all paths from setting file
     :return An array which contain all the directory model
     '''
     settingPath = cls.settingPath()
     fm = NSFileManager.defaultManager()
     paths = NSMutableArray.array()
     settings = NSMutableDictionary.dictionary()
     if fm.fileExistsAtPath_isDirectory_(settingPath, None)[0]:
         settingFile = NSData.dataWithContentsOfFile_(settingPath)
         jsonData = NSJSONSerialization.JSONObjectWithData_options_error_(
             settingFile, 0, None)[0]
         settings['startup'] = jsonData['startup']
         settings['api_key'] = jsonData['api_key']
         for item in jsonData['paths']:
             directory = Directory.alloc().initWithDict_(item)
             paths.addObject_(directory)
         settings['paths'] = paths
     else:
         settings['startup'] = True
         settings['api_key'] = ''
         settings['paths'] = paths
     return settings
def get_directory_contents(directory_model):
    directory = Directory.get(Directory.key == directory_model.key)
    directories = Directory.select().where(Directory.parent_directory == directory.id)
    directory_model.directories = [directory for directory in directories]
    return directory_model
Exemple #19
0
 def dir_exists(self):
     path, name = split_url(self.get_current_path())
     result = Directory.gql('WHERE path = :path AND name = :name',
                            path=path,
                            name=name)
     return (path == "") or result.count() != 0
Exemple #20
0
 def get_request_dir(self):
   """
   Получение директории, с которой производится работа
   """
   parent, name = self.split_parent_dir()
   return Directory.gql('WHERE path = :1 AND name = :2', parent, name)
Exemple #21
0
 def get_request_dir_subdirs(self):
   """
   Получение поддиректорий директории, с которой производится работа
   """
   dirs = Directory.gql('WHERE path = :1', self.dir_url())
   return dirs.fetch(dirs.count())
Exemple #22
0
 def get_subdirs(self):
     result = Directory.gql('WHERE path = :1', self.get_current_path())
     return result.fetch(result.count())