Angular-Filemanagerによるファイル管理

ブログ記事の転載です。インストール後の不具合・改善点などフォローします。

Raspberry PiやOrange Piなどのディスプレイを接続しないコンピュータボード内の一部設定ファイルを、他端末のウェブブラウザで一元管理するため、AngularJSによるファイルマネージャーAngular-Filemanagerをインストールします。予め指定された管理ディレクトリ内で、ファイルのアップロード・ダウンロード・編集操作などがブラウザ経由で実行でき、ユーザによるアプリ機能の修正・アップグレード・カスタマイズを容易にします。

Angular-Filemanager

前回のブログで紹介したウェブサーバ lighttppdphp-cgi(php7.0-cgi) は既にインストールされているものとします。

1.Angular-Filemanagerのダウンロード・インストール

SSH接続でRaspberry Pi またはOrange Piにアクセスします。ウェブサーバディレクトリへ移動し Angular-Filemanager をダウンロードします。

$ cd /var/www/html
$ git clone GitHub - joni2back/angular-filemanager: JavaScript File Manager Material Design Folder Explorer Navigator Browser Manager in AngularJS with CSS3 Responsive (with FTP in PHP / Java / Node)

2.各種ファイルの設定・編集

$ cd angular-filemanager

index.html を以下の様に編集します。 bridges/php-local の設定が反映されるようにします。

  <script type="text/javascript">
    //example to override angular-filemanager default config
    angular.module('FileManagerApp').config(['fileManagerConfigProvider', function (config) {
      var defaults = config.$get();
      config.set({
        appName: 'angular-filemanager',
        pickCallback: function(item) {
          var msg = 'Picked %s "%s" for external use'
            .replace('%s', item.type)
            .replace('%s', item.fullPath());
          window.alert(msg);
        },
        
        listUrl: 'bridges/php-local/index.php',
        uploadUrl: 'bridges/php-local/index.php',
        renameUrl: 'bridges/php-local/index.php',
        copyUrl: 'bridges/php-local/index.php',
        moveUrl: 'bridges/php-local/index.php',
        removeUrl: 'bridges/php-local/index.php',
        editUrl: 'bridges/php-local/index.php',
        getContentUrl: 'bridges/php-local/index.php',
        createFolderUrl: 'bridges/php-local/index.php',
        downloadFileUrl: 'bridges/php-local/index.php',
        downloadMultipleUrl: 'bridges/php-local/index.php',
        compressUrl: 'bridges/php-local/index.php',
        extractUrl: 'bridges/php-local/index.php',
        permissionsUrl: 'bridges/php-local/index.php',

        allowedActions: angular.extend(defaults.allowedActions, {
                upload: true,
                rename: true,
                move: true,
                copy: true,
                edit: true,
                changePermissions: false,
                compress: true,
                compressChooseName: true,
                extract: true,
                download: true,
                downloadMultiple: true,
                preview: true,
                remove: true,
                createFolder: true,          
          		pickFiles: false,
				pickFolders: false
        }),
            isEditableFilePattern: /\.(m3u|txt|cnf|cfg|conf|ini|xml|sh)$/i,
            isImageFilePattern: /\.(jpe?g|gif|bmp|png|svg|tiff?)$/i,
            isExtractableFilePattern: /\.(gz|tar|rar|g?zip)$/i
      });
    }]);
  </script>
</head>

<body class="ng-cloak">
  <angular-filemanager></angular-filemanager>
</body>

bridges/php-local/index.php 内で管理フォルダを指定します。指定するフォルダは任意です。

下記は angular-filemanager 内に files フォルダを作成した場合です。

/**
 * Takes two arguments
 * - base path without last slash (default: '$currentDirectory/../files')
 * - language (default: 'en'); mute_errors (default: true, will call ini_set('display_errors', 0))
 */
$fileManagerApi = new FileManagerApi(__DIR__ . '/../../files');

bridges/php-local/LocalBridge/FileManagerApi.php を一部編集します。

ファイルのアップロード時にファイル名を変更する機能を無効とします。

private function uploadAction($path, $files)
{
    $path = $this->canonicalizePath($this->basePath . $path);

    foreach ($_FILES as $file) {
        $uploaded = move_uploaded_file(
            $file['tmp_name'],
            $path . DIRECTORY_SEPARATOR . $file['name']
        );
        if ($uploaded === false) {
            return false;
        }
    }

    return true;
}

3.lighttpdダイジェスト認証

https://redmine.lighttpd.net/projects/1/wiki/HowToBasicAuth

ユーザ、レルム、パスワードの組合せからMD5によるパスワード暗号化を行います。

まず /etc/lighttpdlighthttp.conf によるダイジェスト認証モジュール関連の設定を追加します。

server.modules = (
	"mod_access",
	"mod_alias",
	"mod_compress",
	"mod_redirect",
	"mod_auth",              ----->ここを追加
#   "mod_rewrite",
)

server.document-root        = "/var/www/html"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"
server.port                 = 80


index-file.names            = ( "index.php", "index.html", "index.lighttpd.html" )
url.access-deny             = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/javascript", "text/css", "text/html", "text/plain" )

# default listening port for IPv6 falls back to the IPv4 port
## Use ipv6 if available
#include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

#以下追加
auth.debug = 2
auth.backend                = "htdigest"
auth.backend.htdigest.userfile = "/etc/lighttpd/lighttpd.user"

# note this entry is relative to the server.document-root
auth.require = ( "/angular-filemanager" =>
   (
    "method" => "basic",
    "realm" => "admin realm",
    "require" => "user=admin"
   )
)

上記ユーザ"admin"、レルム"admin realm"と認証パスワードをMD5により関連付けて暗号化します。

一連の作業を次のperlスクリプトで実行します。

$ sudo pico lighttpd_auth_perl

以下内容です。

#!/usr/bin/perl

print "User: ";
$user = <>;
chomp $user;
print "Realm: ";
$realm = <>;
chomp $realm;

use Term::ReadKey;
{
  ReadMode('noecho');
  print "Password: ";
  $password = ReadLine(0);
  chomp $password;
  print "\nPassword again: ";
  $password2 = ReadLine(0);
  chomp $password2;
  ReadMode('normal');
  print "\n";

  if($password ne $password2)
  {
    print "Passwords don't match\n";
    redo;
  }
}

print "$user:$realm:";
open(MD5, "|md5sum | cut -b -32") or die;
print MD5 "$user:$realm:$password";
close(MD5);

実行権を付与し、実行します。

$ sudo chmod +x lighthtpd_auth_perl
$ sudo ./lighthtpd_auth_perl

ユーザ、レルム、パスワードを入力すると暗号化された文字列が出力されます。

admin:admin realm:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

上記出力結果を /etc/lighttpd/lighttpd.user にコピーします。

lifgttpdサービスを再起動してファイルマネージャにアクセス、認証画面が表示されユーザとパスワードを入力すれば初期画面が表示されます。

$ sudo service lighttpd restart

現時点での最新バージョンへの対応

index.html内でraw source codeを有効にするため以下の箇所をアンコメント、コメント化します。

変更後

<script src=“src/js/app.js”></script>
<script src=“src/js/directives/directives.js”></script>
<script src=“src/js/filters/filters.js”></script>
<script src=“src/js/providers/config.js”></script>
<script src=“src/js/entities/chmod.js”></script>
<script src=“src/js/entities/item.js”></script>
<script src=“src/js/services/apihandler.js”></script>
<script src=“src/js/services/apimiddleware.js”></script>
<script src=“src/js/services/filenavigator.js”></script>
<script src=“src/js/providers/translations.js”></script>
<script src=“src/js/controllers/main.js”></script>
<script src=“src/js/controllers/selector-controller.js”></script>
<link href=“src/css/animations.css” rel=“stylesheet”>
<link href=“src/css/dialogs.css” rel=“stylesheet”>
<link href=“src/css/main.css” rel=“stylesheet”>

<!–
<link href=“dist/angular-filemanager.min.css” rel=“stylesheet”>
<script src=“dist/angular-filemanager.min.js”></script>
–>

src/js/providers/config.js内でphp-localを有効にするため、以下のように変更します。

変更後

listUrl: 'bridges/php-local/index.php',
uploadUrl: 'bridges/php-local/index.php',
renameUrl: 'bridges/php-local/index.php',
copyUrl: 'bridges/php-local/index.php',
moveUrl: 'bridges/php-local/index.php',
removeUrl: 'bridges/php-local/index.php',
editUrl: 'bridges/php-local/index.php',
getContentUrl: 'bridges/php-local/index.php',
createFolderUrl: 'bridges/php-local/index.php',
downloadFileUrl: 'bridges/php-local/index.php',
downloadMultipleUrl: 'bridges/php-local/index.php',
compressUrl: 'bridges/php-local/index.php',
extractUrl: 'bridges/php-local/index.php',
permissionsUrl: 'bridges/php-local/index.php',
basePath: '/files',

ベースディレクトリ(上記のbasePathで指定)filesを以下のphp-localに作成します。

$ sudo mkdir /var/www/html/filemanager/bridges/php-local/files

念の為ディレクトリのアクセス権を再設定します。

$ sudo chown -R www-data:www-data /var/www/html/filemanager
$ sudo chmod -R 755 /var/www/html/filemanager