Added documentation

This commit is contained in:
Max Nuding 2021-11-27 12:52:29 +01:00
parent ae4eb30a73
commit 29b429e239
Signed by: phlaym
GPG Key ID: A06651BAB6777237
4 changed files with 166 additions and 17 deletions

View File

@ -1,9 +1,13 @@
<?php <?php
session_start(); session_start();
/** require autoloading to manage namespaces */
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
use PhotoPrismUpload\API\PhotoPrism; use PhotoPrismUpload\API\PhotoPrism;
use PhotoPrismUpload\Entities\Album;
/** @var string $footer Footer text which links to the Gitea repo */
$footer = '<footer style="position: fixed;bottom: 0;left: 0;">' $footer = '<footer style="position: fixed;bottom: 0;left: 0;">'
.'<a href="/git/phlaym/photoprismupload">Ich bin Open Source</a></footer>'; .'<a href="/git/phlaym/photoprismupload">Ich bin Open Source</a></footer>';
?> ?>
@ -61,7 +65,11 @@ $footer = '<footer style="position: fixed;bottom: 0;left: 0;">'
grid-row: 3; grid-row: 3;
justify-self: right; justify-self: right;
} }
#error, #fileProgress, #totalProgress, label[for="fileProgress"], label[for="totalProgress"] { #error,
#fileProgress,
#totalProgress,
label[for="fileProgress"],
label[for="totalProgress"] {
display:none; display:none;
grid-column: 1; grid-column: 1;
} }
@ -88,7 +96,7 @@ $footer = '<footer style="position: fixed;bottom: 0;left: 0;">'
width: 100%; width: 100%;
} }
#viewAlbum { #viewAlbum {
#grid-row: 7; grid-row: 7;
} }
footer { footer {
margin: 8px; margin: 8px;
@ -98,8 +106,13 @@ $footer = '<footer style="position: fixed;bottom: 0;left: 0;">'
<body> <body>
<?php <?php
/** @var array $config configuration options */
$config = require(__DIR__ . '/config.php'); $config = require(__DIR__ . '/config.php');
/** @var PhotoPrism $api API object to interface with PhotoPrism */
$api = new PhotoPrism($config); $api = new PhotoPrism($config);
/** @var Album[] $albums List of PhotoPrism albums */
$albums = []; $albums = [];
try { try {
$api->login(); $api->login();
@ -111,9 +124,15 @@ if (!isset($_POST['submit'])) {
if (!isset($_GET['token'])) { if (!isset($_GET['token'])) {
die('Sorry, kein Zugriff' . $footer . '</body></html>'); die('Sorry, kein Zugriff' . $footer . '</body></html>');
} }
/** @var string $token Tokens for which album(s) are visible in the dropdown */
$token = $_GET['token']; $token = $_GET['token'];
/** @var string[] $tokens List of album tokens */
$tokens = explode(',', $token); $tokens = explode(',', $token);
$album_url = null;
/** @var string $album_url URL path to the selected album */
$album_url = '/';
try { try {
$albums = $api->getAlbumsByTokens($tokens); $albums = $api->getAlbumsByTokens($tokens);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -128,10 +147,13 @@ if (!isset($_POST['submit'])) {
<label for="album">Zu Album hinzufügen</label> <label for="album">Zu Album hinzufügen</label>
<select name="album" id="album"> <select name="album" id="album">
<option value="" data-url="/">---</option> <option value="" data-url="/">---</option>
<?php foreach ($albums as $album) { <?php
$selected = $album->token === $token ? ' selected' : ''; /** @var Album $album Current PhotoPrism albums */
foreach ($albums as $album) {
/** @var string $selected Selected attribute of the option */
$selected = $album->token === $token ? ' selected ' : '';
if ($album->token === $token) { if ($album->token === $token) {
$album_url = $album->getUrlPath(); $album_url = $album->getUrlPath() ?? '/';
} }
echo '<option value="' echo '<option value="'
. $album->uid . $album->uid
@ -143,7 +165,6 @@ if (!isset($_POST['submit'])) {
. $album->title . $album->title
. '</option>\n'; . '</option>\n';
} }
$album_url ??= '/';
$album_url = "https://photos.phlaym.net{$album_url}"; $album_url = "https://photos.phlaym.net{$album_url}";
?> ?>
</select> </select>

View File

@ -4,15 +4,32 @@ namespace PhotoPrismUpload\API;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Handler\HandlerInterface; use Monolog\Handler\HandlerInterface;
/** Simple factory to create a logger without needing to set stream handlers every time */
class LoggerFactory class LoggerFactory
{ {
private static $handlers = []; private static $handlers = [];
public static function addHandler(HandlerInterface $handler) /**
* Add a new handler which is automatically added to the list of handlers
* for all _future_ loggers
*
* @param HandlerInterface $handler The handler to add
*
* @return void
*/
public static function addHandler(HandlerInterface $handler): void
{ {
self::$handlers[] = $handler; self::$handlers[] = $handler;
} }
public static function create(string $name)
/**
* Create a new Logger with the specified name
*
* @param string $name
*
* @return Logger
*/
public static function create(string $name): Logger
{ {
$l = new Logger($name); $l = new Logger($name);
$l->setHandlers(self::$handlers); $l->setHandlers(self::$handlers);

View File

@ -9,14 +9,35 @@ use PhotoPrismUpload\Exceptions\NetworkException;
use PhotoPrismUpload\Exceptions\AuthenticationException; use PhotoPrismUpload\Exceptions\AuthenticationException;
use PhotoPrismUpload\Entities\Album; use PhotoPrismUpload\Entities\Album;
/**
* The main API class to interface with PhotoPrism
*/
class PhotoPrism class PhotoPrism
{ {
protected string $base_url = 'https://photos.phlaym.net'; /** @var string $base_url Base URL of the PhotoPrism instance */
public string $base_url = 'https://photos.phlaym.net';
/** @var string $api_url API URL of the PhotoPrism instance */
protected string $api_url = ''; protected string $api_url = '';
/** @var string|null $session_id Session id of the currently logged in user */
protected ?string $session_id = null; protected ?string $session_id = null;
/** @var array $config Configuration options */
protected array $config; protected array $config;
/** @var LoggerInterface $logger Logger object */
protected LoggerInterface $logger; protected LoggerInterface $logger;
/**
* Creates a new Photoprism API object from the configuration
*
* @param array $config Configuration dictionary
* @param string|null $log_path Path where the log files end up in.
* Will be set to `$log_path = __DIR__.'/logs/log.log';` if empty.
*
* @return void
*/
public function __construct( public function __construct(
array $config, array $config,
?string $log_path = null ?string $log_path = null
@ -33,6 +54,16 @@ class PhotoPrism
} }
} }
/**
* Parse headers from a cURL HTTP response.
* Returns an array with the keys `headers` and `content`.
* The former is an array containing the headers (header name as key, value as value).
* The latter is a string with the body of the response
*
* @param string $response The complete response, containing the headers and body
*
* @return array
*/
private function parseHeaders(string $response): array private function parseHeaders(string $response): array
{ {
$response = explode("\r\n\r\n", $response, 2); $response = explode("\r\n\r\n", $response, 2);
@ -62,6 +93,19 @@ class PhotoPrism
return ['headers' => $header_arr, 'content' => $content]; return ['headers' => $header_arr, 'content' => $content];
} }
/**
* Sends a HTTP request using cURL
* Returns the body of the response
*
* @param string $method -The HTTP method to use
* @param string $path The HTTP request path without the API URL
* @param array $data Request data to send
* @param string $content_type Content-Type to use
*
* @throws NetworkException on failure
*
* @return string The response body
*/
private function makeRequest( private function makeRequest(
string $method, string $method,
string $path, string $path,
@ -119,7 +163,10 @@ class PhotoPrism
} }
if (empty($output) || $output === false) { if (empty($output) || $output === false) {
$e = new NetworkException("No answer from" . $url, 0); $e = new NetworkException("No answer from" . $url, 0);
$this->logger->error("Error sending request", ['Exception' => $e]); $this->logger->error(
"Error sending request. No answer from server",
['Exception' => print_r($e, true)]
);
throw $e; throw $e;
} }
if ($http_status === 0) { if ($http_status === 0) {
@ -130,13 +177,22 @@ class PhotoPrism
} }
$result = $this->parseHeaders($output); $result = $this->parseHeaders($output);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->logger->error("Error sending request", ['Exception' => $e]); $this->logger->error("Error sending request", ['Exception' => print_r($e, true)]);
throw new NetworkException("Error sending request to " . $url, 0, $e); throw new NetworkException("Error sending request to " . $url, 0, $e);
} }
return $result['content']; return $result['content'];
} }
public function login(bool $force = false) /**
* Log in to PhotoPrism.
* If already logged in nothing happens.
* No check whether the session is still valid is performed
* @throws AuthenticationException on failure
*
* @param bool $force -Force re-login even if already logged in
*/
public function login(bool $force = false): void
{ {
if (!empty($this->session_id) && !$force) { if (!empty($this->session_id) && !$force) {
$this->logger->info('Skipping login, already logged in'); $this->logger->info('Skipping login, already logged in');
@ -157,6 +213,15 @@ class PhotoPrism
$this->logger->debug('Session ID: ' . $this->session_id); $this->logger->debug('Session ID: ' . $this->session_id);
} }
/**
* Fetches albums from PhotoPrism
* @throws NetworkException on failure
*
* @param int $count -Maximum amount of albums to fetch
* @param int $offset -Number of albums to skip
* @return Album[]
*/
public function getAlbums(int $count = 1000, int $offset = 0): array public function getAlbums(int $count = 1000, int $offset = 0): array
{ {
$data = [ $data = [
@ -179,10 +244,19 @@ class PhotoPrism
return $albums; return $albums;
} }
/**
* Fetches albums from PhotoPrism which can be viewed with the provided tokens
* @throws NetworkException on failure
* @param string[] $tokens -A list of tokens by which the albms are filtered
* @param int $count -Maximum amount of albums to fetch
* @param int $offset -Number of albums to skip
* @return Album[]
*/
public function getAlbumsByTokens(array $tokens, int $count = 1000, int $offset = 0): array public function getAlbumsByTokens(array $tokens, int $count = 1000, int $offset = 0): array
{ {
$this->logger->debug('getAlbumsByToken'); $this->logger->debug('getAlbumsByToken');
$albums = $this->getAlbums($count, 0); $albums = $this->getAlbums($count, $offset);
$visibleAlbums = []; $visibleAlbums = [];
foreach ($albums as $album) { foreach ($albums as $album) {
$token = $this->getAlbumToken($album); $token = $this->getAlbumToken($album);
@ -198,10 +272,19 @@ class PhotoPrism
return $visibleAlbums; return $visibleAlbums;
} }
/**
* Fetches the secret token of an album
* @throws NetworkException on failure
*
* @param Album $album -The album which's toke should be fetched
* @return string|null Album token or null if the album is private
*/
public function getAlbumToken($album): ?string public function getAlbumToken($album): ?string
{ {
$uid = is_string($album) ? $album : $album->uid; $uid = is_string($album) ? $album : $album->uid;
$res = $this->makeRequest('GET', '/albums/' . $uid . '/links'); $res = $this->makeRequest('GET', '/albums/' . $uid . '/links');
/** @var array $response */
$response = json_decode($res, true)[0]; $response = json_decode($res, true)[0];
if (!empty($response['error'])) { if (!empty($response['error'])) {
throw new NetworkException($response['error']); throw new NetworkException($response['error']);
@ -213,12 +296,18 @@ class PhotoPrism
return $response['Token']; return $response['Token'];
} }
public function uploadPhotos(?string $album = null) /**
* Upload photos, optionally add them to a specific album
* @throws NetworkException on failure
* @param string|null $album -The album uid to which the photos should be aded
*/
public function uploadPhotos(?string $album = null): void
{ {
$path = time(); $path = time();
$url = '/upload/'.$path; $url = '/upload/'.$path;
$import_url = '/import'.$url; $import_url = '/import'.$url;
foreach ($_FILES['files']['tmp_name'] as $key => $value) { foreach (array_keys($_FILES['files']['tmp_name']) as $key) {
$file_tmpname = $_FILES['files']['tmp_name'][$key]; $file_tmpname = $_FILES['files']['tmp_name'][$key];
$this->logger->info('Uploading ' . $file_tmpname . ' to ' . $url); $this->logger->info('Uploading ' . $file_tmpname . ' to ' . $url);
$filename = basename($_FILES['files']['name'][$key]); $filename = basename($_FILES['files']['name'][$key]);
@ -230,6 +319,7 @@ class PhotoPrism
} }
$this->logger->info('Importing files'); $this->logger->info('Importing files');
/** @var string[] $albums */
$albums = empty($album) ? [] : [$album]; $albums = empty($album) ? [] : [$album];
$import_data = ["move" => true, "albums" => $albums]; $import_data = ["move" => true, "albums" => $albums];

View File

@ -1,16 +1,30 @@
<?php <?php
namespace PhotoPrismUpload\Entities; namespace PhotoPrismUpload\Entities;
use Monolog\Logger;
use PhotoPrismUpload\API\LoggerFactory; use PhotoPrismUpload\API\LoggerFactory;
/** A PhotoPrism Album */
class Album class Album
{ {
/** @var string $uid Unique Id of the album */
public string $uid = ''; public string $uid = '';
/** @var string $slug URL slug of the album */
public string $slug = ''; public string $slug = '';
/** @var string $title Title of the album */
public string $title = ''; public string $title = '';
/** @var string|null $token Secret token of the album. Needs to be set by the API */
public ?string $token = null; public ?string $token = null;
/**
* Creates a new album from the api response
*
* @param array $response Photoprism API response containing an album object
*
* @return void
*/
public function __construct( public function __construct(
array $response array $response
) { ) {
@ -20,6 +34,13 @@ class Album
$this->logger = LoggerFactory::create('PhotoPrismUpload.Album'); $this->logger = LoggerFactory::create('PhotoPrismUpload.Album');
} }
/**
* Gets the URL path for this album.
* Starts with a leading /
* Returns null if the album's token is not set
*
* @return string|null
*/
public function getUrlPath(): ?string public function getUrlPath(): ?string
{ {
if (empty($this->token)) { if (empty($this->token)) {