One place for hosting & domains

      Seafile

      Como Sincronizar e Compartilhar Seus Arquivos com o Seafile no Debian 10


      Introdução

      O Seafile é uma plataforma de compartilhamento e sincronização de arquivos open-source e auto-hospedada. Os usuários podem armazenar e, opcionalmente, criptografar dados em seus próprios servidores, tendo o espaço de armazenamento como única limitação. Com o Seafile, você pode compartilhar arquivos e pastas usando links de sincronização multi-plataformas e protegidos por senha para arquivos com datas de validade. O recurso de versionamento de arquivo significa que os usuários podem restaurar arquivos ou pastas excluídos e modificados.

      Neste tutorial, você instalará e configurará o Seafile em um servidor Debian 10. Você usará o MariaDB (a variante padrão do MySQL no Debian 10) para armazenar dados para os diferentes componentes do Seafile e o Apache como servidor proxy para lidar com o tráfego web. Após concluir este tutorial, você poderá usar a interface web para acessar o Seafile a partir de clientes móveis ou desktops, permitindo sincronizar e compartilhar seus arquivos com outros usuários ou grupos no servidor ou com o público.

      Pré-requisitos

      Antes de começar este guia, você precisará do seguinte:

      Passo 1 — Criando Bancos de Dados para os Componentes do Seafile

      O Seafile requer três componentes para funcionar corretamente:

      • Seahub: O front-end web do Seafile, escrito em Python usando o framework web Django. A partir do Seahub, você pode acessar, gerenciar e compartilhar seus arquivos usando um navegador web.
      • Seafile server: O daemon do serviço de dados que gerencia o upload, o download e a sincronização de arquivos raw. Você não interage diretamente com o servidor, mas usa um programa cliente ou a interface web Seahub.
      • Ccnet server: O daemon de serviço RPC para permitir a comunicação interna entre os diferentes componentes do Seafile. Por exemplo, quando você usa o Seahub, ele pode acessar dados do servidor Seafile usando o serviço RPC Ccnet.

      Cada um desses componentes armazena seus dados separadamente em seu próprio banco de dados. Neste passo, você criará os três bancos de dados MariaDB e um usuário antes de prosseguir com a configuração do servidor.

      Primeiro, efetue login no servidor usando SSH com seu nome de usuário e endereço IP:

      ssh sammy@ip_do_seu_servidor
      

      Conecte-se ao servidor de banco de dados MariaDB como administrador (root):

      No prompt do MariaDB, use o seguinte comando SQL para criar o usuário do banco de dados:

      • CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'senha';

      Em seguida, você criará os seguintes bancos de dados para armazenar os dados dos três componentes do Seafile:

      • ccnet-db para o servidor Ccnet.
      • seahub-db para o frontend web Seahub.
      • seafile-db para o servidor Seafile.

      No prompt do MariaDB, crie seus bancos de dados:

      • CREATE DATABASE 'ccnet-db' CHARACTER SET = 'utf8';
      • CREATE DATABASE 'seafile-db' CHARACTER SET = 'utf8';
      • CREATE DATABASE 'seahub-db' CHARACTER SET = 'utf8';

      Em seguida, conceda todos os privilégios ao seu usuário de banco de dados para acessar e fazer alterações nesses bancos de dados:

      • GRANT ALL PRIVILEGES ON 'ccnet-db'.* to 'sammy'@localhost;
      • GRANT ALL PRIVILEGES ON 'seafile-db'.* to 'sammy'@localhost;
      • GRANT ALL PRIVILEGES ON 'seahub-db'.* to 'sammy'@localhost;

      Saia do prompt do MariaDB digitando exit:

      Agora que você criou um usuário e os bancos de dados necessários para armazenar os dados de cada um dos componentes do Seafile, você instalará as dependências para baixar o pacote do servidor Seafile.

      Passo 2 — Instalando Dependências e Baixando o Seafile

      Algumas partes do Seafile são escritas em Python e, portanto, requerem módulos e programas adicionais em Python para funcionar. Neste passo, você instalará essas dependências necessárias antes de baixar e extrair o pacote do servidor Seafile.

      Para instalar as dependências usando o apt, execute o seguinte comando:

      • sudo apt install python-setuptools python-pip python-urllib3 python-requests python-mysqldb ffmpeg

      As dependências python-setuptools e python-pip supervisionam a instalação e o gerenciamento de pacotes Python. Os pacotes python-urllib3 e python-orders fazem solicitações aos websites. Finalmente, o python-mysqldb é uma biblioteca para usar o MariaDB no Python e o ffmpeg lida com arquivos multimídia.

      O Seafile requer o Pillow, uma biblioteca python para processamento de imagens, e o moviepy para lidar com as miniaturas dos arquivos de filmes. Estes módulos não estão disponíveis no repositório de pacotes Debian, então instale-os com o pip:

      • sudo pip install Pillow moviepy

      Agora que você instalou as dependências necessárias, pode fazer o download do pacote do servidor Seafile.

      O Seafile cria diretórios adicionais durante a instalação. Para mantê-los todos organizados, crie um novo diretório e mude para ele:

      Você pode baixar a versão mais recente (7.0.4 no momento em que este artigo foi escrito) do servidor Seafile a partir do website do projeto executando este comando:

      • wget https://download.seadrive.org/seafile-server_7.0.4_x86-64.tar.gz

      O Seafile distribui o download como um arquivo tar compactado, o que significa que você precisará extraí-lo antes de continuar. Extraia o arquivo usando tar:

      • tar -zxvf seafile-server_7.0.4_x86-64.tar.gz

      Agora mude para o diretório extraído:

      Nesta fase, você baixou e extraiu o pacote do servidor Seafile e também instalou as dependências necessárias. Agora você está pronto para configurar o servidor Seafile.

      Passo 3 — Configurando o Servidor Seafile

      O Seafile precisa de algumas informações sobre sua configuração antes de iniciar os serviços pela primeira vez. Isso inclui detalhes como o nome do domínio, a configuração do banco de dados e o caminho em que os dados serão armazenados. Para iniciar a série de solicitações de perguntas para fornecer essas informações, você pode executar o script setup_seafile_mysql.sh, incluído no arquivo que você extraiu na etapa anterior.

      Execute o script usando o bash:

      • bash setup-seafile-mysql.sh

      Pressione ENTER para continuar quando solicitado.

      O script agora fará uma série de perguntas. Onde quer que os padrões sejam mencionados, pressionar a tecla ENTER utilizará esse valor.

      Este tutorial usa Seafile como o nome do servidor, mas você pode alterá-lo se desejar:

      Question 1
      
      What is the name of the server?
      It will be displayed on the client. 3 - 15 letters or digits
      [ server name ] Seafile
      

      Para Question 2, digite o nome de domínio para esta instância do Seafile.

      Question 2
      
      What is the ip or domain of the server?.
      For example: www.mycompany.com, 192.168.1.101
      [ This server's ip or domain ] seu_domínio
      

      Pressione ENTER para aceitar o valor padrão para a Question 3. Se você configurou o armazenamento externo, por exemplo, usando NFS ou armazenamento em bloco, precisará especificar o caminho para esse local aqui.

      Question 3
      
      Where do you want to put your seafile data?
      Please use a volume with enough free space
      [ default "/home/sammy/seafile/seafile-data" ]
      

      Para Question 4 pressione ENTER para aceitar o número da porta padrão.

      Question 4
      
      Which port do you want to use for the seafile fileserver?
      [ default "8082" ]
      

      O próximo prompt permite confirmar a configuração do banco de dados. Você pode criar novos bancos de dados ou usar bancos de dados existentes para configuração. Para este tutorial, você criou os bancos de dados necessários no Passo 1, então selecione a opção 2 aqui.

      -------------------------------------------------------
      Please choose a way to initialize seafile databases:
      -------------------------------------------------------
      
      [1] Create new ccnet/seafile/seahub databases
      [2] Use existing ccnet/seafile/seahub databases
      
      [ 1 or 2 ] 2
      

      As perguntas 6 a 9 estão relacionadas ao servidor de banco de dados MariaDB. Você precisa fornecer o nome de usuário e a senha do usuário MySQL que você criou no Passo 1, mas você pode pressionar ENTER para aceitar os valores padrão para host e port.

      
      What is the host of mysql server?
      
      [ default "localhost" ]
      
      What is the port of mysql server?
      
      [ default "3306" ]
      
      Which mysql user to use for seafile?
      
      [ mysql user for seafile ] sammy
      
      What is the password for mysql user "seafile"?
      
      [ password for seafile ] senha
      

      Após fornecer a senha, o script solicitará os nomes dos bancos de dados do Seafile. Use ccnet-db, seafile-db, e seahub-db para este tutorial. O script verificará se há uma conexão bem-sucedida aos bancos de dados antes de continuar exibindo um resumo da configuração inicial.

      Enter the existing database name for ccnet:
      [ ccnet database ] ccnet-db
      
      verifying user "sammy" access to database ccnet-db ...  done
      
      Enter the existing database name for seafile:
      [ seafile database ] seafile-db
      
      verifying user "sammy" access to database seafile-db ...  done
      
      Enter the existing database name for seahub:
      [ seahub database ] seahub-db
      
      verifying user "sammy For this tutorial you have" access to database seahub-db ...  done
      
      ---------------------------------
      This is your configuration
      ---------------------------------
      
          server name:            Seafile
          server ip/domain:       seu_domínio
      
          seafile data dir:       /home/sammy/seafile/seafile-data
          fileserver port:        8082
      
          database:               use existing
          ccnet database:         ccnet-db
          seafile database:       seafile-db
          seahub database:        seahub-db
          database user:          sammy
      
      --------------------------------
      Press ENTER to continue, or Ctrl-C to abort
      ---------------------------------
      

      Pressione ENTER para confirmar.

      Output

      Generating ccnet configuration ... done Successly create configuration dir /home/sammy/seafile/ccnet. Generating seafile configuration ... done Generating seahub configuration ... ---------------------------------------- Now creating seahub database tables ... ---------------------------------------- creating seafile-server-latest symbolic link ... done ----------------------------------------------------------------- Your seafile server configuration has been finished successfully. ----------------------------------------------------------------- run seafile server: ./seafile.sh { start | stop | restart } run seahub server: ./seahub.sh { start <port> | stop | restart <port> } ----------------------------------------------------------------- If you are behind a firewall, remember to allow input/output of these tcp ports: ----------------------------------------------------------------- port of seafile fileserver: 8082 port of seahub: 8000 When problems occur, Refer to https://github.com/haiwen/seafile/wiki for information.

      Você estará executando o Seafile atrás do Apache, o que você já permitiu através do firewall do servidor. Portanto, você não precisa se preocupar em abrir as portas 8082 e 8000 e pode ignorar essa parte da saída.

      Você concluiu a configuração inicial do servidor. No próximo passo, você configurará o servidor web Apache antes de iniciar os serviços do Seafile.

      Passo 4 — Configurando o Servidor Web Apache

      Nesta etapa, você configurará o servidor web Apache para encaminhar todas as solicitações ao Seafile. O uso do Apache dessa maneira permite que você use uma URL sem um número de porta, habilite conexões HTTPS com o Seafile e utilize a funcionalidade de armazenamento em cache fornecida pelo Apache para obter melhor desempenho.

      Para começar a encaminhar solicitações, você precisará habilitar o módulo proxy_http na configuração do Apache. Este módulo fornece recursos para fazer proxy de solicitações HTTP e HTTPS. O seguinte comando ativará o módulo:

      Nota: Os módulos Apache rewrite e ssl também são necessários para esta configuração. Você já ativou esses módulos como parte da configuração do Let’s Encrypt no segundo tutorial do Apache listado na seção de pré-requisitos.

      Em seguida, atualize a configuração do virtual host do seu_domínio para encaminhar solicitações ao servidor de arquivos Seafile e à interface web Seahub.

      Abra o arquivo de configuração em um editor de texto:

      • sudo nano /etc/apache2/sites-enabled/seu_domínio-le-ssl.conf

      As linhas de ServerAdmin até SSLCertificateKeyFile fazem parte da configuração inicial do Apache e do Let’s Encrypt que você definiu nos tutoriais de pré-requisito. Adicione o conteúdo destacado, iniciando em Alias e terminando com a diretiva ProxyPassReverse:

      /etc/apache2/sites-enabled/your_domain-le-ssl.conf

      
      <IfModule mod_ssl.c>
      <VirtualHost *:443>
          ServerAdmin admin@seu_domínio_de_email
          ServerName seu_domínio
          ServerAlias www.seu_domínio
          DocumentRoot /var/www/seu_domínio/html
          ErrorLog ${APACHE_LOG_DIR}/seu_domínio-error.log
          CustomLog ${APACHE_LOG_DIR}/seu_domínio-access.log combined
      
          Include /etc/letsencrypt/options-ssl-apache.conf
          SSLCertificateFile /etc/letsencrypt/live/seu_domínio/fullchain.pem
          SSLCertificateKeyFile /etc/letsencrypt/live/seu_domínio/privkey.pem
      
          Alias /media  /home/sammy/seafile/seafile-server-latest/seahub/media
          <Location /media>
              Require all granted
          </Location>
      
          # seafile fileserver
          ProxyPass /seafhttp http://127.0.0.1:8082
          ProxyPassReverse /seafhttp http://127.0.0.1:8082
          RewriteEngine On
          RewriteRule ^/seafhttp - [QSA,L]
      
          # seahub web interface
          SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
          ProxyPass / http://127.0.0.1:8000/
          ProxyPassReverse / http://127.0.0.1:8000/
      </VirtualHost>
      </IfModule>
      

      A diretiva Alias mapeia o caminho da URL seu_domínio/media para um caminho local no sistema de arquivos que o Seafile utiliza. A diretiva seguinte, Location, habilita o acesso ao conteúdo deste diretório. As diretivas ProxyPass e ProxyPassReverse fazem o Apache agir como um proxy reverso para este host, encaminhando solicitações para / e /seafhttp para a interface web e para o servidor de arquivos Seafile em execução nas portas do host local 8000 e 8082 respectivamente. A diretiva RewriteRule passa todas as solicitações para /seafhttp inalteradas e interrompe o processamento de novas regras ([QSA,L]).

      Salve e saia do arquivo.

      Teste se há algum erro de sintaxe na configuração do virtual host:

      • sudo apache2ctl configtest

      Se ele informar Syntax OK, então não há problemas com sua configuração. Reinicie o Apache para que as alterações entrem em vigor:

      • sudo systemctl restart apache2

      Agora você configurou o Apache para atuar como um proxy reverso para o servidor de arquivos Seafile e o Seahub. Em seguida, você atualizará as URLs na configuração do Seafile antes de iniciar os serviços.

      Passo 5 — Atualizando a Configuração do Seafile e Iniciando os Serviços

      Agora que você está usando o Apache para fazer proxy de todas as solicitações para o Seafile, será necessário atualizar as URLs nos arquivos de configuração do Seafile no diretório conf usando um editor de texto antes de iniciar o serviço Seafile.

      Abra ccnet.conf em um editor de texto:

      • nano /home/sammy/seafile/conf/ccnet.conf

      Perto do topo do arquivo, dentro do bloco [General], está a diretiva SERVICE_URL. Ela parecerá assim:

      Update /home/sammy/seafile/conf/ccnet.conf

      . . .
      SERVICE_URL=http://www.example.com:8000
      . . .
      

      Modifique essa configuração para apontar para o seu domínio. Verifique se a URL fornecida usa o protocolo HTTPS e se não inclui nenhum número de porta:

      Update /home/sammy/seafile/conf/ccnet.conf

      . . .
      SERVICE_URL = https://seu_domínio
      . . .
      

      Salve e saia do arquivo depois de adicionar o conteúdo.

      Agora abra seahub_settings.py em um editor de texto:

      • nano /home/sammy/seafile/conf/seahub_settings.py

      Adicione uma configuração FILE_SERVER_ROOT no arquivo para especificar o caminho onde o servidor de arquivos está atendendo a uploads e downloads de arquivos:

      Update /home/sammy/seafile/conf/seahub_settings.py

      # -*- coding: utf-8 -*-
      SECRET_KEY = "..."
      FILE_SERVER_ROOT = 'https://seu_domínio/seafhttp'
      # ...
      

      Salve e saia do arquivo seahub_settings.py.

      Agora você pode iniciar o serviço Seafile e a interface Seahub:

      • cd /home/sammy/seafile/seafile-server-7.0.4
      • ./seafile.sh start
      • ./seahub.sh start

      Como esta é a primeira vez que você inicia o serviço Seahub, ele solicita que você crie uma conta de administrador. Digite um endereço de email válido e uma senha para este usuário administrador:

      Output

      What is the email for the admin account? [ admin email ] admin@seu_domínio_de_email What is the password for the admin account? [ admin password ] senha Enter the password again: [ admin password again ] senha ---------------------------------------- Successfully created seafile admin ---------------------------------------- Seahub is started Done.

      Abra https://seu_domínio em um navegador web e faça login usando seu endereço de e-mail e a senha de administrador do Seafile.

      Login screen of the Seafile web interface

      Uma vez logado com sucesso, você pode acessar a interface de administração ou criar novos usuários.

      Agora que você verificou que a interface web está funcionando corretamente, você pode ativar esses serviços para iniciar automaticamente na inicialização do sistema no próximo passo.

      Passo 6 — Habilitando o Servidor Seafile para Iniciar na Inicialização do Sistema

      Para permitir que o servidor de arquivos e a interface web iniciem automaticamente na inicialização, você pode criar seus respectivos arquivos de serviço systemd e ativá-los.

      Crie um arquivo de serviço systemd para o servidor de arquivos Seafile:

      • sudo nano /etc/systemd/system/seafile.service

      Adicione o seguinte conteúdo ao arquivo:

      Create /etc/systemd/system/seafile.service

      [Unit]
      Description=Seafile
      After=network.target mysql.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seafile.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seafile.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Aqui, as linhas ExecStart e ExecStop indicam os comandos que são executados para iniciar e parar o serviço Seafile. O serviço será executado com sammy como User e Group. A linha After especifica que o serviço Seafile será iniciado após o início da rede e do serviço MariaDB.

      Salve o seafile.service e saia.

      Crie um arquivo de serviço systemd para a interface web do Seahub:

      • sudo nano /etc/systemd/system/seahub.service

      Isso é semelhante ao serviço Seafile. A única diferença é que a interface web é iniciada após o serviço Seafile. Adicione o seguinte conteúdo a este arquivo:

      Create /etc/systemd/system/seahub.service

      [Unit]
      Description=Seafile hub
      After=network.target seafile.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seahub.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seahub.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Salve o seahub.service e saia.

      Você pode aprender mais sobre arquivos de unidade do systemd no tutorial Understanding Systemd Units and Unit Files.

      Por fim, para permitir que os serviços Seafile e Seahub sejam iniciados automaticamente na inicialização, execute os seguintes comandos:

      • sudo systemctl enable seafile.service
      • sudo systemctl enable seahub.service

      Quando o servidor é reiniciado, o Seafile irá iniciar automaticamente.

      Neste ponto, você concluiu a configuração do servidor e agora pode testar cada um dos serviços.

      Passo 7 — Testando as Funcionalidades de Sincronização e Compartilhamento de Arquivos

      Neste passo, você testará a funcionalidade de sincronização e compartilhamento de arquivos do servidor que você configurou e garantirá que elas estejam funcionando corretamente. Para fazer isso, você precisará instalar o programa cliente do Seafile em um computador separado e/ou em um dispositivo móvel.

      Visite a página de download no site da Seafile e siga as instruções para instalar a versão mais recente do programa cliente no seu computador. Os clientes do Seafile estão disponíveis para as várias distribuições do Linux (Ubuntu, Debian, Fedora, Centos/RHEL, Arch Linux), MacOS e Windows. Clientes móveis estão disponíveis para dispositivos Android e iPhone/iPad nas respectivas lojas de aplicativos.

      Depois de instalar o cliente Seafile, você pode testar a funcionalidade de sincronização e compartilhamento de arquivos.

      Abra o programa cliente do Seafile no seu computador ou dispositivo. Aceite o local padrão para a pasta Seafile e clique em Next.

      Na próxima janela, digite o endereço do servidor, nome de usuário e senha e clique em Login.

      Na página inicial, clique com o botão direito do mouse em My Library e clique em Sync this library. Aceite o valor padrão para o local no seu computador ou dispositivo.

      Seafile client — Sync the default library

      Adicione um arquivo, por exemplo, um documento ou uma foto, na pasta My Library. Depois de algum tempo, o arquivo será carregado no servidor. A captura de tela a seguir mostra o arquivo photo.jpg copiado para a pasta My Library.

      Add a file to the default library from the computer

      Agora, efetue login na interface web em https://seu_domínio e verifique se seu arquivo está presente no servidor.

      My Library page to verify file sync

      Clique em Share ao lado do arquivo para gerar um link de download para esse arquivo que você pode compartilhar.

      Você verificou que a sincronização de arquivos está funcionando corretamente e que você pode usar o Seafile para sincronizar e compartilhar arquivos e pastas de vários dispositivos.

      Conclusão

      Neste tutorial, você configurou uma instância privada de um servidor Seafile. Agora você pode começar a usar o servidor para sincronizar arquivos, adicionar usuários e grupos e compartilhar arquivos entre eles ou com o público sem depender de um serviço externo.

      Quando uma nova versão do servidor estiver disponível, consulte a seção upgrade do manual para verificar os passos para executar uma atualização.



      Source link

      How To Sync and Share Your Files with Seafile on Debian 10


      Introduction

      Seafile is an open-source, self-hosted, file synchronization and sharing platform. Users can store and optionally encrypt data on their own servers with storage space as the only limitation. With Seafile you can share files and folders using cross-platform syncing and password-protected links to files with expiration dates. A file-versioning feature means that users can restore deleted and modified files or folders.

      In this tutorial, you will install and configure Seafile on a Debian 10 server. You will use MariaDB (the default MySQL variant on Debian 10) to store data for the different components of Seafile, and Apache as the proxy server to handle the web traffic. After completing this tutorial, you will be able use the web interface to access Seafile from desktop or mobile clients, allowing you to sync and share your files with other users or groups on the server or with the public.

      Prerequisites

      Before you begin this guide, you’ll need the following:

      Step 1 — Creating Databases for the Seafile Components

      Seafile requires three components in order to work properly:

      • Seahub: Seafile’s web frontend, written in Python using the Django web framework. From Seahub you can access, manage, and share your files using a web browser.
      • Seafile server: The data service daemon that manages the raw file upload, download, and synchronization. You do not interact with the server directly, but instead use a client program or the Seahub web interface.
      • Ccnet server: The RPC service daemon to enable internal communication between the different components of Seafile. For example, when you use Seahub, it is able to access data from the Seafile server using the Ccnet RPC service.

      Each of these components stores its data separately in its own database. In this step you will create the three MariaDB databases and a user before proceeding to set up the server.

      First, log in to the server using SSH with your username and IP address:

      ssh sammy@your_server_ip
      

      Connect to the MariaDB database server as administrator (root):

      At the MariaDB prompt, use the following SQL command to create the database user:

      • CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';

      Next, you will create the following databases to store the data of the three Seafile components:

      • ccnet-db for the Ccnet server.
      • seahub-db for the Seahub web frontend.
      • seafile-db for the Seafile file server.

      At the MariaDB prompt, create your databases:

      • CREATE DATABASE 'ccnet-db' CHARACTER SET = 'utf8';
      • CREATE DATABASE 'seafile-db' CHARACTER SET = 'utf8';
      • CREATE DATABASE 'seahub-db' CHARACTER SET = 'utf8';

      Then, grant all privileges to your database user to access and make changes in these databases:

      • GRANT ALL PRIVILEGES ON 'ccnet-db'.* to 'sammy'@localhost;
      • GRANT ALL PRIVILEGES ON 'seafile-db'.* to 'sammy'@localhost;
      • GRANT ALL PRIVILEGES ON 'seahub-db'.* to 'sammy'@localhost;

      Exit the MariaDB prompt by typing exit:

      Now that you have created a user and the databases required to store the data for each of the Seafile components, you will install dependencies to download the Seafile server package.

      Step 2 — Installing Dependencies and Downloading Seafile

      Some parts of Seafile are written in Python and therefore require additional Python modules and programs to work. In this step, you will install these required dependencies before downloading and extracting the Seafile server package.

      To install the dependencies using apt run the following command:

      • sudo apt install python-setuptools python-pip python-urllib3 python-requests python-mysqldb ffmpeg

      The python-setuptools and python-pip dependencies oversee installing and managing Python packages. The python-urllib3 and python-requests packages make requests to websites. Finally, the python-mysqldb is a library for using MariaDB from Python and ffmpeg handles multimedia files.

      Seafile requires Pillow, a python library for image processing, and moviepy to handle movie file thumbnails. These modules are not available in the Debian package repository, so instead install them with pip:

      • sudo pip install Pillow moviepy

      Now that you have installed the necessary dependencies, you can download the Seafile server package.

      Seafile creates additional directories during setup. To keep them all organized, create a new directory and change into it:

      You can now download the latest version (7.0.4 as of this writing) of the Seafile server from the project website by running the following command:

      • wget https://download.seadrive.org/seafile-server_7.0.4_x86-64.tar.gz

      Seafile distributes the download as a compressed tar archive, which means you will need to extract it before proceeding. Extract the archive using tar:

      • tar -zxvf seafile-server_7.0.4_x86-64.tar.gz

      Now change into the extracted directory:

      At this stage, you have downloaded and extracted the Seafile server package and have also installed the necessary dependencies. You are now ready to configure the Seafile server.

      Step 3 — Configuring the Seafile Server

      Seafile needs some information about your setup before you start the services for the first time. This includes details like the domain name, the database configuration, and the path where it will store data. To initiate the series of question prompts to provide this information, you can run the script setup_seafile_mysql.sh, which is included in the archive you extracted in the previous step.

      Run the script using bash:

      • bash setup-seafile-mysql.sh

      Press ENTER to continue when prompted.

      The script will now prompt you with a series of questions. Wherever defaults are mentioned, pressing the ENTER key will use that value.

      This tutorial uses Seafile as the server name, but you can change it if you'd like:

      Question 1
      
      What is the name of the server?
      It will be displayed on the client. 3 - 15 letters or digits
      [ server name ] Seafile
      

      For Question 2, enter the domain name for this Seafile instance.

      Question 2
      
      What is the ip or domain of the server?.
      For example: www.mycompany.com, 192.168.1.101
      [ This server's ip or domain ] your_domain
      

      Press ENTER to accept the default value for Question 3. If you have set up external storage, for example, using NFS or block storage, you will need to specify the path to that location here instead.

      Question 3
      
      Where do you want to put your seafile data?
      Please use a volume with enough free space
      [ default "/home/sammy/seafile/seafile-data" ]
      

      For Question 4 press ENTER to accept the default port number.

      Question 4
      
      Which port do you want to use for the seafile fileserver?
      [ default "8082" ]
      

      The next prompt allows you to confirm the database configuration. You can create new databases or use existing databases for setup. For this tutorial you have created the necessary databases in Step 1, so select option 2 here.

      -------------------------------------------------------
      Please choose a way to initialize seafile databases:
      -------------------------------------------------------
      
      [1] Create new ccnet/seafile/seahub databases
      [2] Use existing ccnet/seafile/seahub databases
      
      [ 1 or 2 ] 2
      

      Questions 6–9 relate to the MariaDB database server. You need to provide the username and password of the MySQL user that you created in Step 1, but you can press ENTER to accept the default values for host and port.

      
      What is the host of mysql server?
      
      [ default "localhost" ]
      
      What is the port of mysql server?
      
      [ default "3306" ]
      
      Which mysql user to use for seafile?
      
      [ mysql user for seafile ] sammy
      
      What is the password for mysql user "seafile"?
      
      [ password for seafile ] password
      

      After providing the password, the script will request the names of the Seafile databases. Use ccnet-db, seafile-db, and seahub-db for this tutorial. The script will then verify if there is a successful connection to the databases before proceeding to display a summary of the initial configuration.

      Enter the existing database name for ccnet:
      [ ccnet database ] ccnet-db
      
      verifying user "sammy" access to database ccnet-db ...  done
      
      Enter the existing database name for seafile:
      [ seafile database ] seafile-db
      
      verifying user "sammy" access to database seafile-db ...  done
      
      Enter the existing database name for seahub:
      [ seahub database ] seahub-db
      
      verifying user "sammyFor this tutorial you have" access to database seahub-db ...  done
      
      ---------------------------------
      This is your configuration
      ---------------------------------
      
          server name:            Seafile
          server ip/domain:       your_domain
      
          seafile data dir:       /home/sammy/seafile/seafile-data
          fileserver port:        8082
      
          database:               use existing
          ccnet database:         ccnet-db
          seafile database:       seafile-db
          seahub database:        seahub-db
          database user:          sammy
      
      --------------------------------
      Press ENTER to continue, or Ctrl-C to abort
      ---------------------------------
      

      Press ENTER to confirm.

      Output

      Generating ccnet configuration ... done Successly create configuration dir /home/sammy/seafile/ccnet. Generating seafile configuration ... done Generating seahub configuration ... ---------------------------------------- Now creating seahub database tables ... ---------------------------------------- creating seafile-server-latest symbolic link ... done ----------------------------------------------------------------- Your seafile server configuration has been finished successfully. ----------------------------------------------------------------- run seafile server: ./seafile.sh { start | stop | restart } run seahub server: ./seahub.sh { start <port> | stop | restart <port> } ----------------------------------------------------------------- If you are behind a firewall, remember to allow input/output of these tcp ports: ----------------------------------------------------------------- port of seafile fileserver: 8082 port of seahub: 8000 When problems occur, Refer to https://github.com/haiwen/seafile/wiki for information.

      You will be running Seafile behind Apache, which you've already allowed through your server's firewall. Hence, you don't need to worry about opening ports 8082 and 8000 as well and you can ignore that part of the output.

      You have completed the initial configuration of the server. In the next step, you will configure the Apache web server before starting the Seafile services.

      Step 4 — Configuring the Apache Web Server

      In this step, you will configure the Apache web server to forward all requests to Seafile. Using Apache in this manner allows you to use a URL without a port number, enable HTTPS connections to Seafile, and make use of the caching functionality that Apache provides for better performance.

      To begin forwarding requests, you will need to enable the proxy_http module in the Apache configuration. This module provides features for proxying HTTP and HTTPS requests. The following command will enable the module:

      Note: The Apache rewrite and ssl modules are also required for this setup. You have already enabled these modules as part of configuring Let's Encrypt in the second Apache tutorial listed in the prerequisites section.

      Next, update the virtual host configuration of your_domain to forward requests to the Seafile file server and to the Seahub web interface.

      Open the configuration file in a text editor:

      • sudo nano /etc/apache2/sites-enabled/your_domain-le-ssl.conf

      The lines from ServerAdmin to SSLCertificateKeyFile are part of the initial Apache and Let's Encrypt configuration that you set up in the prerequisite tutorials. Add the highlighted content, beginning at Alias and ending with the ProxyPassReverse directive:

      /etc/apache2/sites-enabled/your_domain-le-ssl.conf

      
      <IfModule mod_ssl.c>
      <VirtualHost *:443>
          ServerAdmin admin@your_email_domain
          ServerName your_domain
          ServerAlias www.your_domain
          DocumentRoot /var/www/your_domain/html
          ErrorLog ${APACHE_LOG_DIR}/your_domain-error.log
          CustomLog ${APACHE_LOG_DIR}/your_domain-access.log combined
      
          Include /etc/letsencrypt/options-ssl-apache.conf
          SSLCertificateFile /etc/letsencrypt/live/your_domain/fullchain.pem
          SSLCertificateKeyFile /etc/letsencrypt/live/your_domain/privkey.pem
      
          Alias /media  /home/sammy/seafile/seafile-server-latest/seahub/media
          <Location /media>
              Require all granted
          </Location>
      
          # seafile fileserver
          ProxyPass /seafhttp http://127.0.0.1:8082
          ProxyPassReverse /seafhttp http://127.0.0.1:8082
          RewriteEngine On
          RewriteRule ^/seafhttp - [QSA,L]
      
          # seahub web interface
          SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
          ProxyPass / http://127.0.0.1:8000/
          ProxyPassReverse / http://127.0.0.1:8000/
      </VirtualHost>
      </IfModule>
      

      The Alias directive maps the URL path your_domain/media to a local path in the file system that Seafile uses. The following Location directive enables access to content in this directory. The ProxyPass and ProxyPassReverse directives make Apache act as a reverse proxy for this host, forwarding requests to / and /seafhttp to the Seafile web interface and file server running on local host ports 8000 and 8082 respectively. The RewriteRule directive passes all requests to /seafhttp unchanged and stops processing further rules ([QSA,L]).

      Save and exit the file.

      Test if there are any syntax errors in the virtual host configuration:

      • sudo apache2ctl configtest

      If it reports Syntax OK, then there are no issues with your configuration. Restart Apache for the changes to take effect:

      • sudo systemctl restart apache2

      You have now configured Apache to act as a reverse proxy for the Seafile file server and Seahub. Next, you will update the URLs in Seafile's configuration before starting the services.

      Step 5 — Updating Seafile's Configuration and Starting Services

      As you are now using Apache to proxy all requests to Seafile, you will need to update the URLs in Seafile's configuration files in the conf directory using a text editor before you start the Seafile service.

      Open ccnet.conf in a text editor:

      • nano /home/sammy/seafile/conf/ccnet.conf

      Near the top of the file, within the [General] block, is the SERVICE_URL directive. It will look like this:

      Update /home/sammy/seafile/conf/ccnet.conf

      . . .
      SERVICE_URL=http://www.example.com:8000
      . . .
      

      Modify this setting to point to your domain. Be sure that the URL you provide uses the HTTPS protocol, and that it does not include any port number:

      Update /home/sammy/seafile/conf/ccnet.conf

      . . .
      SERVICE_URL = https://your_domain
      . . .
      

      Save and exit the file once you have added the content.

      Now open seahub_settings.py in a text editor:

      • nano /home/sammy/seafile/conf/seahub_settings.py

      Add a FILE_SERVER_ROOT setting in the file to specify the path where the file server is listening for file uploads and downloads:

      Update /home/sammy/seafile/conf/seahub_settings.py

      # -*- coding: utf-8 -*-
      SECRET_KEY = "..."
      FILE_SERVER_ROOT = 'https://your_domain/seafhttp'
      # ...
      

      Save and exit seahub_settings.py.

      Now you can start the Seafile service and the Seahub interface:

      • cd /home/sammy/seafile/seafile-server-7.0.4
      • ./seafile.sh start
      • ./seahub.sh start

      As this is the first time you have started the Seahub service, it will prompt you to create an admin account. Enter a valid email address and a password for this admin user:

      Output

      What is the email for the admin account? [ admin email ] admin@your_email_domain What is the password for the admin account? [ admin password ] password-here Enter the password again: [ admin password again ] password-here ---------------------------------------- Successfully created seafile admin ---------------------------------------- Seahub is started Done.

      Open https://your_domain in a web browser and log in using your Seafile admin email address and password.

      Login screen of the Seafile web interface

      Once logged in successfully, you can access the admin interface or create new users.

      Now that you have verified the web interface is working correctly, you can enable these services to start automatically at system boot in the next step.

      Step 6 — Enabling the Seafile Server to Start at System Boot

      To enable the file server and the web interface to start automatically at boot, you can create their respective systemd service files and activate them.

      Create a systemd service file for the Seafile file server:

      • sudo nano /etc/systemd/system/seafile.service

      Add the following content to the file:

      Create /etc/systemd/system/seafile.service

      [Unit]
      Description=Seafile
      After=network.target mysql.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seafile.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seafile.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Here, the ExectStart and ExecStop lines indicate the commands that run to start and stop the Seafile service. The service will run with sammy as the User and Group. The After line specifies that the Seafile service will start after the networking and MariaDB service has started.

      Save seafile.service and exit.

      Create a systemd service file for the Seahub web interface:

      • sudo nano /etc/systemd/system/seahub.service

      This is similar to the Seafile service. The only difference is that the web interface is started after the Seafile service. Add the following content to this file:

      Create /etc/systemd/system/seahub.service

      [Unit]
      Description=Seafile hub
      After=network.target seafile.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seahub.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seahub.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Save seahub.service and exit.

      You can learn more about systemd unit files in the Understanding Systemd Units and Unit Files tutorial.

      Finally, to enable both the Seafile and Seahub services to start automatically at boot, run the following commands:

      • sudo systemctl enable seafile.service
      • sudo systemctl enable seahub.service

      When the server is rebooted, Seafile will start automatically.

      At this point, you have completed setting up the server, and can now test each of the services.

      Step 7 — Testing File Syncing and Sharing Functionality

      In this step, you will test the file synchronization and sharing functionality of the server you have set up and ensure they are working correctly. To do this, you will need to install the Seafile client program on a separate computer and/or a mobile device.

      Visit the download page on the Seafile website and follow the instructions to install the latest version of the client program on your computer. Seafile clients are available for the various distributions of Linux (Ubuntu, Debian, Fedora, Centos/RHEL, Arch Linux), MacOS, and Windows. Mobile clients are available for Android and iPhone/iPad devices from the respective app stores.

      Once you have installed the Seafile client, you can test the file synchronization and sharing functionality.

      Open the Seafile client program on your computer or device. Accept the default location for the Seafile folder and click Next.

      In the next window, enter the server address, username, and password, then click Login.

      At the home page, right click on My Library and click Sync this library. Accept the default value for the location on your computer or device.

      Seafile client — Sync the default library

      Add a file, for example a document or a photo, into the My Library folder. After some time, the file will upload to the server. The following screenshot shows the file photo.jpg copied to the My Library folder.

      Add a file to the default library from the computer

      Now, log in to the web interface at https://your_domain and verify that your file is present on the server.

      My Library page to verify file sync

      Click on Share next to the file to generate a download link for this file that you can share.

      You have verified that the file synchronization is working correctly and that you can use Seafile to sync and share files and folders from multiple devices.

      Conclusion

      In this tutorial you set up a private instance of a Seafile server. Now you can start using the server to synchronize files, add users and groups, and share files between them or with the public without relying on an external service.

      When a new release of the server is available, please consult the upgrade section of the manual for steps to perform an upgrade.



      Source link

      How To Sync and Share Your Files with Seafile on Debian 9


      The author selected Electronic Frontier Foundation Inc to receive a donation as part of the Write for DOnations program.

      Introduction

      Seafile is an open-source, self-hosted, file synchronization and sharing platform. Users can store and optionally encrypt data on their own servers with storage space as the only limitation. With Seafile you can share files and folders using cross-platform syncing and password-protected links to files with expiration dates. A file-versioning feature means that users can restore deleted and modified files or folders.

      In this tutorial, you will install and configure Seafile on a Debian 9 server. You will use MariaDB (the default MySQL variant on Debian 9) to store data for the different components of Seafile, and Apache as the proxy server to handle the web traffic. After completing this tutorial, you will be able use the web interface to access Seafile from desktop or mobile clients, allowing you to sync and share your files with other users or groups on the server or with the public.

      Prerequisites

      Before you begin this guide, you’ll need the following:

      • One Debian 9 server with a minimum of 2GB of RAM set up by following this Initial Server Setup with Debian 9 tutorial, including a sudo non-root user and a firewall.
      • An Apache web server with a virtual host configured for the registered domain by following How To Install the Apache Web Server on Debian 9.
      • An SSL certificate installed on your server by following this How To Secure Apache with Let’s Encrypt on Debian 9 tutorial.
      • A fully registered domain name. This tutorial will use example.com throughout.
      • Both of the following DNS records set up for your server. You can follow this introduction to DigitalOcean DNS for details on how to add them.

        • An A record with example.com pointing to your server’s public IP address.
        • An A record with www.example.com pointing to your server’s public IP address.
      • A MariaDB database server installed and configured. Follow the steps in the How To Install MariaDB on Debian 9 tutorial. Skip Step 3 of this tutorial — “(Optional) Adjusting User Authentication and Privileges”. You will only be making local connections to the database server, so changing the authentication method for the root user is not necessary.

      Step 1 — Creating Databases for the Seafile Components

      Seafile requires three components in order to work properly. These three components are:

      • Seahub: Seafile’s web frontend, written in Python using the Django web framework. From Seahub you can access, manage, and share your files using a web browser.
      • Seafile server: The data service daemon that manages the raw file upload, download, and synchronization. You do not interact with the server directly, but use one of the client programs or the Seahub web interface.
      • Ccnet server: The RPC service daemon to enable internal communication between the different components of Seafile. For example, when you use Seahub, it is able to access data from the Seafile server using the Ccnet RPC service.

      Each of these components stores its data separately in its own database. In this step you will create the three MariaDB databases and a user before proceeding to set up the server.

      First, log in to the server using SSH with your username and IP address:

      ssh sammy@your_server_ip
      

      Connect to the MariaDB database server as administrator (root):

      At the MariaDB prompt, use the following SQL command to create the database user:

      • CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';

      Next, you will create the following databases to store the data of the three Seafile components:

      • ccnet-db for the Ccnet server.
      • seahub-db for the Seahub web frontend.
      • seafile-db for the Seafile file server.

      At the MariaDB prompt, create your databases:

      • CREATE DATABASE `ccnet-db` CHARACTER SET = 'utf8';
      • CREATE DATABASE `seafile-db` CHARACTER SET = 'utf8';
      • CREATE DATABASE `seahub-db` CHARACTER SET = 'utf8';

      Then, grant all privileges to the Seafile database user to access and make changes in these databases:

      • GRANT ALL PRIVILEGES ON `ccnet-db`.* to `sammy`@localhost;
      • GRANT ALL PRIVILEGES ON `seafile-db`.* to `sammy`@localhost;
      • GRANT ALL PRIVILEGES ON `seahub-db`.* to `sammy`@localhost;

      Exit the MariaDB prompt by typing exit:

      Now that you have created a user and the databases required to store the data for each of the Seafile components, you will install dependencies to download the Seafile server package.

      Step 2 — Installing Dependencies and Downloading Seafile

      Some parts of Seafile are written in Python and therefore require additional Python modules and programs to work. In this step, you will install these required dependencies before downloading and extracting the Seafile server package.

      To install the dependencies using apt run the following command:

      • sudo apt install python-setuptools python-pip python-urllib3 python-requests python-mysqldb ffmpeg

      The python-setuptools and python-pip dependencies oversee installing and managing Python packages. The python-urllib3 and python-requests packages make requests to websites. Finally, the python-mysqldb is a library for using MariaDB from Python and ffmpeg handles multimedia files.

      Seafile requires Pillow, a python library for image processing, and moviepy to handle movie file thumbnails. These modules are not available in the Debian package repository. You will install them manually using pip:

      • sudo pip install Pillow==4.3.0 moviepy

      Now that you have installed the necessary dependencies, you can download the Seafile server package.

      Seafile creates additional directories during setup. To keep them all organized, create a new directory and change into it:

      You can now download the latest version (6.3.4 as of this writing) of the Seafile server from the website by running the following command:

      • wget https://download.seadrive.org/seafile-server_6.3.4_x86-64.tar.gz

      Seafile distributes the download as a compressed tar archive, which means you will need to extract it before proceeding. Extract the archive using tar:

      • tar -zxvf seafile-server_6.3.4_x86-64.tar.gz

      Now change into the extracted directory:

      At this stage, you have downloaded and extracted the Seafile server package and have also installed the necessary dependencies. You are now ready to configure the Seafile server.

      Step 3 — Configuring the Seafile Server

      Seafile needs some information about your setup before you start the services for the first time. This includes details like the domain name, the database configuration, and the path where it will store data. To initiate the series of question prompts to provide this information, you can run the script setup_seafile_mysql.sh, which is included in the archive you extracted in the previous step.

      Run the script using bash:

      • bash setup-seafile-mysql.sh

      Press ENTER to continue.

      The script will now prompt you with a series of questions. Wherever defaults are mentioned, pressing the ENTER key will use that value.

      This tutorial uses Seafile as the server name, but you can change it if necessary.

      Question 1
      
      What is the name of the server?
      It will be displayed on the client. 3 - 15 letters or digits
      [ server name ] Seafile
      

      Enter the domain name for this Seafile instance.

      Question 2
      
      What is the ip or domain of the server?.
      For example: www.mycompany.com, 192.168.1.101
      [ This server's ip or domain ] example.com
      

      For Question 3 press ENTER to accept the default value. If you have set up external storage, for example, using NFS or block storage, you will need to specify the path to that location here instead.

      Question 3
      
      Where do you want to put your seafile data?
      Please use a volume with enough free space
      [ default "/home/sammy/seafile/seafile-data" ]
      

      For Question 4 press ENTER to accept the default value.

      Question 4
      
      Which port do you want to use for the seafile fileserver?
      [ default "8082" ]
      

      The next prompt allows you to confirm the database configuration. You can create new databases or use existing databases for setup. For this tutorial you have created the necessary databases in Step 1, so select option 2 here.

      -------------------------------------------------------
      Please choose a way to initialize seafile databases:
      -------------------------------------------------------
      
      [1] Create new ccnet/seafile/seahub databases
      [2] Use existing ccnet/seafile/seahub databases
      
      [ 1 or 2 ] 2
      

      Questions 6–9 relate to the MariaDB database server. You will only need to provide the username and password of the mysql user that you created in Step 1. Press ENTER to accept the default values for host and port.

      
      What is the host of mysql server?
      
      [ default "localhost" ]
      
      What is the port of mysql server?
      
      [ default "3306" ]
      
      Which mysql user to use for seafile?
      
      [ mysql user for seafile ] sammy
      
      What is the password for mysql user "seafile"?
      
      [ password for seafile ] password
      

      After providing the password, the script will request the names of the Seafile databases. Use ccnet-db, seafile-db, and seahub-db for this tutorial. The script will then verify if there is a successful connection to the databases before proceeding to display a summary of the initial configuration.

      Enter the existing database name for ccnet:
      [ ccnet database ] ccnet-db
      
      verifying user "sammy" access to database ccnet-db ...  done
      
      Enter the existing database name for seafile:
      [ seafile database ] seafile-db
      
      verifying user "sammy" access to database seafile-db ...  done
      
      Enter the existing database name for seahub:
      [ seahub database ] seahub-db
      
      verifying user "sammy" access to database seahub-db ...  done
      
      ---------------------------------
      This is your configuration
      ---------------------------------
      
          server name:            Seafile
          server ip/domain:       example.com
      
          seafile data dir:       /home/sammy/seafile/seafile-data
          fileserver port:        8082
      
          database:               use existing
          ccnet database:         ccnet-db
          seafile database:       seafile-db
          seahub database:        seahub-db
          database user:          sammy
      
      --------------------------------
      Press ENTER to continue, or Ctrl-C to abort
      ---------------------------------
      

      Press ENTER to confirm.

      Output

      Generating ccnet configuration ... done Successly create configuration dir /home/sammy/seafile/ccnet. Generating seafile configuration ... done Generating seahub configuration ... ---------------------------------------- Now creating seahub database tables ... ---------------------------------------- creating seafile-server-latest symbolic link ... done ----------------------------------------------------------------- Your seafile server configuration has been finished successfully. ----------------------------------------------------------------- run seafile server: ./seafile.sh { start | stop | restart } run seahub server: ./seahub.sh { start <port> | stop | restart <port> } ----------------------------------------------------------------- If you are behind a firewall, remember to allow input/output of these tcp ports: ----------------------------------------------------------------- port of seafile fileserver: 8082 port of seahub: 8000 When problems occur, Refer to https://github.com/haiwen/seafile/wiki for information.

      As you will be running Seafile behind Apache, opening ports 8082 and 8000 in the firewall is not necessary, so you can ignore this part of the output.

      You have completed the initial configuration of the server. In the next step, you will configure the Apache web server before starting the Seafile services.

      Step 4 — Configuring the Apache Web Server

      In this step, you will configure the Apache web server to forward all requests to Seafile. Using Apache in this manner allows you to use a URL without a port number, enable HTTPS connections to Seafile, and make use of the caching functionality that Apache provides for better performance.

      To begin forwarding requests, you will need to enable the proxy_http module in the Apache configuration. This module provides features for proxying HTTP and HTTPS requests. The following command will enable the module:

      Note: The Apache rewrite and ssl modules are also required for this setup. You have already enabled these modules as part of configuring Let's Encrypt in the second Apache tutorial listed in the prerequisites section.

      Next, update the virtual host configuration of example.com to forward requests to the Seafile file server and to the Seahub web interface.

      Open the configuration file in a text editor:

      • sudo nano /etc/apache2/sites-enabled/example.com-le-ssl.conf

      The lines from ServerAdmin to SSLCertificateKeyFile are part of the initial Apache and Let's Encrypt configuration that you set up as part of the prerequisite. Add the highlighted content, beginning at Alias and ending with the ProxyPassReverse directive:

      /etc/apache2/sites-enabled/example.com-le-ssl.conf

      
      <IfModule mod_ssl.c>
      <VirtualHost *:443>
          ServerAdmin admin@example.com
          ServerName example.com
          ServerAlias www.example.com
          DocumentRoot /var/www/example.com/html
          ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
          CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
      
          Include /etc/letsencrypt/options-ssl-apache.conf
          SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
          SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
      
          Alias /media  /home/sammy/seafile/seafile-server-latest/seahub/media
          <Location /media>
              Require all granted
          </Location>
      
          # seafile fileserver
          ProxyPass /seafhttp http://127.0.0.1:8082
          ProxyPassReverse /seafhttp http://127.0.0.1:8082
          RewriteEngine On
          RewriteRule ^/seafhttp - [QSA,L]
      
          # seahub web interface
          SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
          ProxyPass / http://127.0.0.1:8000/
          ProxyPassReverse / http://127.0.0.1:8000/
      </VirtualHost>
      </IfModule>
      

      The Alias directive maps the URL path example.com/media to a local path in the file system that Seafile uses. The following Location directive enables access to content in this directory. The ProxyPass and ProxyPassReverse directives make Apache act as a reverse proxy for this host, forwarding requests to / and /seafhttp to the Seafile web interface and file server running on local host ports 8000 and 8082 respectively. The RewriteRule directive passes all requests to /seafhttp unchanged and stops processing further rules ([QSA,L]).

      Save and exit the file.

      Test if there are any syntax errors in the virtual host configuration:

      • sudo apache2ctl configtest

      If it reports Syntax OK, then there are no issues with your configuration. Restart Apache for the changes to take effect:

      • sudo systemctl restart apache2

      You have now configured Apache to act as a reverse proxy for the Seafile file server and Seahub. Next, you will update the URLs in Seafile's configuration before starting the services.

      Step 5 — Updating Seafile's Configuration and Starting Services

      As you are now using Apache to proxy all requests to Seafile, you will need to update the URLs in Seafile's configuration files in the conf directory using a text editor before you start the Seafile service.

      Open ccnet.conf in a text editor:

      • nano /home/sammy/seafile/conf/ccnet.conf

      Modify the SERVICE_URL setting in the file to point to the new HTTPS URL without the port number, for example:

      Update /home/sammy/seafile/conf/ccnet.conf

      SERVICE_URL = https://example.com
      

      Save and exit the file once you have added the content.

      Now open seahub_settings.py in a text editor:

      • nano /home/sammy/seafile/conf/seahub_settings.py

      You can now add a FILE_SERVER_ROOT setting in the file to specify the path where the file server is listening for file uploads and downloads:

      Update /home/sammy/seafile/conf/seahub_settings.py

      # -*- coding: utf-8 -*-
      SECRET_KEY = "..."
      FILE_SERVER_ROOT = 'https://example.com/seafhttp'
      # ...
      

      Save and exit seahub_settings.py.

      Now you can start the Seafile service and the Seahub interface:

      • cd /home/sammy/seafile/seafile-server-6.3.4
      • ./seafile.sh start
      • ./seahub.sh start

      As this is the first time you have started the Seahub service, it will prompt you to create an admin account. Enter a valid email address and a password for this admin user:

      Output

      What is the email for the admin account? [ admin email ] admin@example.com What is the password for the admin account? [ admin password ] password-here Enter the password again: [ admin password again ] password-here ---------------------------------------- Successfully created seafile admin ---------------------------------------- Seahub is started Done.

      Open https://example.com in a web browser and log in using your Seafile admin email address and password.

      Login screen of the Seafile web interface

      Once logged in successfully, you can access the admin interface or create new users.

      Now that you have verified the web interface is working correctly, you can enable these services to start automatically at system boot in the next step.

      Step 6 — Enabling the Seafile Server to Start at System Boot

      To enable the file server and the web interface to start automatically at boot, you can create the respective systemd service files and activate them.

      Create a systemd service file for the Seafile file server:

      • sudo nano /etc/systemd/system/seafile.service

      Add the following content to the file:

      Create /etc/systemd/system/seafile.service

      [Unit]
      Description=Seafile
      After=network.target mysql.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seafile.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seafile.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Here, the ExectStart and ExecStop lines indicate the commands that run to start and stop the Seafile service. The service will run with sammy as the User and Group. The After line specifies that the Seafile service will start after the networking and MariaDB service has started.

      Save seafile.service and exit.

      Create a systemd service file for the Seahub web interface:

      • sudo nano /etc/systemd/system/seahub.service

      This is similar to the Seafile service. The only difference is that the web interface is started after the Seafile service. Add the following content to this file:

      Create /etc/systemd/system/seahub.service

      [Unit]
      Description=Seafile hub
      After=network.target seafile.service
      
      [Service]
      Type=forking
      ExecStart=/home/sammy/seafile/seafile-server-latest/seahub.sh start
      ExecStop=/home/sammy/seafile/seafile-server-latest/seahub.sh stop
      User=sammy
      Group=sammy
      
      [Install]
      WantedBy=multi-user.target
      

      Save seahub.service and exit.

      You can learn more about systemd unit files in the Understanding Systemd Units and Unit Files tutorial.

      Finally, to enable both the Seafile and Seahub services to start automatically at boot, run the following commands:

      • sudo systemctl enable seafile.service
      • sudo systemctl enable seahub.service

      When the server is rebooted, Seafile will start automatically.

      At this point, you have completed setting up the server, and can now test each of the services.

      Step 7 — Testing File Syncing and Sharing Functionality

      In this step, you will test the file synchronization and sharing functionality of the server you have set up and ensure they are working correctly. To do this, you will need to install the Seafile client program on a separate computer and/or a mobile device.

      Visit the download page on the Seafile website and follow the instructions to install the latest version of the program on your computer. Seafile clients are available for the various distributions of Linux (Ubuntu, Debian, Fedora, Centos/RHEL, Arch Linux), MacOS, and Windows. Mobile clients are available for Android and iPhone/iPad devices from the respective app stores.

      Once you have installed the Seafile client, you can test the file synchronization and sharing functionality.

      Open the Seafile client program on your computer or device. Accept the default location for the Seafile folder and click Next.

      In the next window, enter the server address, username, and password, then click Login.

      At the home page, right click on My Library and click Sync this library. Accept the default value for the location on your computer or device.

      Seafile client — Sync the default library

      Add a file, for example a document or a photo, into the My Library folder. After some time, the file will upload to the server. The following screenshot shows the file photo.jpg copied to the My Library folder.

      Add a file to the default library from the computer

      Now, log in to the web interface at https://example.com and verify that your file is present on the server.

      My Library page to verify file sync

      Click on Share next to the file to generate a download link for this file that you can share.

      You have verified that the file synchronization is working correctly and that you can use Seafile to sync and share files and folders from multiple devices.

      Conclusion

      In this tutorial you set up a private instance of a Seafile server. Now you can start using the server to synchronize files, add users and groups, and share files between them or with the public without relying on an external service.

      When a new release of the server is available, please consult the upgrade section of the manual for steps to perform an upgrade.



      Source link