Skip to content

Commit

Permalink
Add flickr uploader for authorised admins
Browse files Browse the repository at this point in the history
  • Loading branch information
Terence Eden committed Jun 30, 2024
1 parent c6b3943 commit a480864
Show file tree
Hide file tree
Showing 7 changed files with 255 additions and 13 deletions.
3 changes: 3 additions & 0 deletions www/.env
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,6 @@ IMAGE_CACHE_PREFIX=""
IMAGE_CACHE_QUALITY="60"
IMAGE_DEFAULT_SIZE="600"
IMAGE_THUMB_SIZE="120"

# Flickr
FLICKR_API_KEY=""
7 changes: 7 additions & 0 deletions www/config/packages/security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ security:
provider: auth0_provider
custom_authenticators:
- auth0.authenticator
flickr:
pattern: ^/flickr
context: user
stateless: false
provider: auth0_provider
custom_authenticators:
- auth0.authenticator
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
Expand Down
27 changes: 26 additions & 1 deletion www/public/js/vision/vision.js.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Modified 2018, Terence Eden
// Modified 2024, Terence Eden

'use strict';

Expand Down Expand Up @@ -102,6 +102,31 @@ function sendFileToCloudVision (content) {
//setTimeout( function() { displayJSON(JSON.parse('{ "responses": [ { "fullTextAnnotation": { "text": "BUFFY ANNE SUMMERS\\n1981 - 2001\\nBELOVED SISTER\\nDEVOTED FRIEND\\nSHE SAVED THE WORLD\\nA LOT" } }] }')); }, 5000);
}

function sendURLToCloudVision (content) {
console.log("sending this url" + content);
// Strip out the file prefix when you convert to json.
var request = {
requests: [{
image: {
content: content
},
features: [{
type: 'TEXT_DETECTION'
}]
}]
};

$('#message').text('Scanning for text...');
console.log("posting " + request);
$.post({
url: CV_URL,
data: JSON.stringify(request),
contentType: 'application/json'
}).fail(function (jqXHR, textStatus, errorThrown) {
$('#message').text('ERRORS: ' + textStatus + ' ' + errorThrown);
}).done(displayJSON);
}

/**
* Displays the results.
*/
Expand Down
114 changes: 114 additions & 0 deletions www/src/Controller/AddController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Symfony\Component\HttpFoundation\Request;

use App\Service\TagsFunctions;
use App\Service\UserFunctions;

use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Tools\DsnParser;
Expand Down Expand Up @@ -57,4 +58,117 @@ public function tags() {
$tagsFunctions->getTags();
}

#[Route("/flickr", name: "flickr_page")]
public function flickr_page(): Response {
$request = Request::createFromGlobals();

$userFunctions = new UserFunctions();

// Only available to Admin users
// Get user from Auth0
$user = $this->getUser();
if( isset( $user ) ) {
$username = $user->getNickname();
$avatar = $user->getPicture();
$provider = explode("|", $user->getUserIdentifier())[0];
$providerID = explode("|", $user->getUserIdentifier())[1];
} else {
die();
}

$userFunctions = new UserFunctions();
$userID = $userFunctions->addUser( $username, $provider, $providerID );

$admin = ( array_search( $userID, explode(",", $_ENV["ADMIN_USERIDS"])) !== false );

if ( false == $admin) { die(); }


// /flickr/?id=AAAA123
$flickrID = $request->query->get("id") ?? false;

if ( $flickrID )
{
$flickrKey = $_ENV["FLICKR_API_KEY"];
$flickrAPI = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key={$flickrKey}&format=json&nojsoncallback=1&photo_id={$flickrID}";

$flickrJSON = file_get_contents($flickrAPI);
$flickrData = json_decode($flickrJSON);

$lat = $flickrData->{"photo"}->{"location"}->{"latitude"};
$long = $flickrData->{"photo"}->{"location"}->{"longitude"};
$farm = $flickrData->{"photo"}->{"farm"};
$server = $flickrData->{"photo"}->{"server"};
$id = $flickrData->{"photo"}->{"id"};
$owner = $flickrData->{"photo"}->{"owner"}->{"nsid"};
$secret = $flickrData->{"photo"}->{"secret"};
$o_secret = $flickrData->{"photo"}->{"originalsecret"};
$license = $flickrData->{"photo"}->{"license"};
$title = $flickrData->{"photo"}->{"title"}->{"_content"};
$description=$flickrData->{"photo"}->{"description"}->{"_content"};
$import = "https://www.flickr.com/photos/{$owner}/{$id}";

// Calculate original photo for importing
$original = "https://farm{$farm}.staticflickr.com/{$server}/{$id}_{$o_secret}_o.jpg";

// Possible inscription
$inscription = $title . " " . $description;

// Get the largest scaled image which is not the original
$flickrSizeAPI = "https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key={$flickrKey}&format=json&nojsoncallback=1&photo_id={$flickrID}";
$flickrSizeJSON = file_get_contents( $flickrSizeAPI );
$flickrSizeData = json_decode( $flickrSizeJSON );
$sizes = $flickrSizeData->{"sizes"}->{"size"};
end( $sizes );
$size = prev( $sizes );
$large = $size->{"source"};
$b64 = base64_encode( file_get_contents( $large ) );

switch ($license) {
case 0:
$license = "All Rights Reserved";
break;
case 1:
$license = "CC BY-NC-SA 2.0";
break;
case 2:
$license = "CC BY-NC 2.0";
break;
case 3:
$license = "CC BY-NC-ND 2.0";
break;
case 4:
$license = "CC BY 2.0";
break;
case 5:
$license = "CC BY-SA 2.0";
break;
case 6:
$license = "CC BY-ND 2.0";
break;
case 7:
$license = "PD";
break;
case 8:
$license = "USG";
break;
}

// Render the page
return $this->render('flickr.html.twig', [
"flickrID" => $flickrID,
"licence" => $license,
"b64" => $b64,
"lat" => $lat,
"long"=> $long,
"inscription" => $inscription,
"original" => $original,
"large" => $large,
"import" => $import
]);
}
// Render the default page
return $this->render('flickr.html.twig', [
]);
}
}
52 changes: 52 additions & 0 deletions www/src/Controller/UploadController.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,56 @@ public function merge(Request $request) {
return $this->redirect("/bench/{$duplicateID}");
}
}

#[Route("/flickrUpload", name: "flickrUpload")]
public function flickrUpload(Request $request) {

// Only available to Admin users
// Get user from Auth0
$user = $this->getUser();
if( isset( $user ) ) {
$username = $user->getNickname();
$avatar = $user->getPicture();
$provider = explode("|", $user->getUserIdentifier())[0];
$providerID = explode("|", $user->getUserIdentifier())[1];
} else {
die();
}

$userFunctions = new UserFunctions();
$userID = $userFunctions->addUser( $username, $provider, $providerID );

$admin = ( array_search( $userID, explode(",", $_ENV["ADMIN_USERIDS"])) !== false );

if ( false == $admin) { die(); }

// TODO - fix hardcoding of Flickr Importer user ID
$userID = 1;

// POST'd data
$inscription = $request->request->get("inscription");
$latitude = $request->request->get("lat");
$longitude = $request->request->get("long");
$licence = $request->request->get("licence");
$importURL = $request->request->get("import");
$originalURL = $request->request->get("original");

// Add the bench
$uploadFunctions = new UploadFunctions();
$benchID = $uploadFunctions->addBench( $inscription, $latitude, $longitude, $userID );

// Get the image
$filename = tempnam( sys_get_temp_dir(), "openbenches" ); // https://www.php.net/manual/en/function.sys-get-temp-dir.php
$photo = file_put_contents( $filename, file_get_contents( $originalURL ));

// Process and save the image
$mediaFunctions = new MediaFunctions();
$metadata = $mediaFunctions->getMediaMetadata( $filename );
$metadata["tmp_name"] = $filename;
$media_type1 = $request->request->get( "media_type1" );
$uploadFunctions->addMedia( $metadata, $media_type1, $benchID, $userID, $licence, $importURL );

// Show the new bench
return $this->redirect("/bench/{$benchID}");
}
}
26 changes: 14 additions & 12 deletions www/src/Service/UploadFunctions.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function updateMedia( $mediaID, $mediaType ) {
}


public function addMedia( $metadata, $media_type, $benchID, $userID ) : int {
public function addMedia( $metadata, $media_type, $benchID, $userID, $licence = "CC BY-SA 4.0", $importURL = null ) : int {
$mediaFunctions = new MediaFunctions();

$file = $metadata["tmp_name"];
Expand All @@ -115,7 +115,7 @@ public function addMedia( $metadata, $media_type, $benchID, $userID ) : int {
if ( !is_dir( $photo_path ) ) {
mkdir( $photo_path, 0777, true );
}
move_uploaded_file($file, $photo_full_path);
rename( $file, $photo_full_path );

// Add the media to the database
$dsnParser = new DsnParser();
Expand All @@ -125,18 +125,20 @@ public function addMedia( $metadata, $media_type, $benchID, $userID ) : int {
$sql = "INSERT INTO `media`
(`mediaID`, `benchID`, `userID`, `sha1`, `licence`, `importURL`, `media_type`, `width`, `height`, `datetime`, `make`, `model`)
VALUES
(NULL, ?, ?, ?, 'CC BY-SA 4.0', null, ?, ?, ?, ?, ?, ?)";
(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $benchID);
$stmt->bindValue(2, $userID);
$stmt->bindValue(3, $sha1);
$stmt->bindValue(4, $media_type);
$stmt->bindValue(5, $metadata["width"]);
$stmt->bindValue(6, $metadata["height"]);
$stmt->bindValue(7, $metadata["datetime"]);
$stmt->bindValue(8, $metadata["make"]);
$stmt->bindValue(9, $metadata["model"]);
$stmt->bindValue( 1, $benchID);
$stmt->bindValue( 2, $userID);
$stmt->bindValue( 3, $sha1);
$stmt->bindValue( 4, $licence);
$stmt->bindValue( 5, $importURL);
$stmt->bindValue( 6, $media_type);
$stmt->bindValue( 7, $metadata["width"]);
$stmt->bindValue( 8, $metadata["height"]);
$stmt->bindValue( 9, $metadata["datetime"]);
$stmt->bindValue(10, $metadata["make"]);
$stmt->bindValue(11, $metadata["model"]);

// Run the query
$results = $stmt->executeQuery();
Expand Down
39 changes: 39 additions & 0 deletions www/templates/flickr.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{% extends "base.html.twig" %}

{# For inclusion in the base #}
{% block title %}Flickr{% endblock %}


{% block body %}
{% if flickrID is defined %}
<h3>Flickr Image "{{ flickrID }}"</h3>
<form action="/flickrUpload" method="post" autocomplete="off">
<a target='_blank' href='{{ original }}'><img id='flickrimg' src='data:image/jpeg;base64,{{ b64 }}' width='512'/></a><br>
<label for="flickrimg">This photo is a:</label>
<select name="media_type1" id="media_type1">
{% set selected = "inscription" %}
{% set media_types_array = media_types() %}
{% for type in media_types_array %}
{% if type.shortName == selected %}
<option value="{{ type.shortName }}" selected="selected">{{ type.longName }}</option>
{% else %}
<option value="{{ type.shortName }}">{{ type.longName }}</option>
{% endif %}
{% endfor %}
</select><br>
<a class='button' onclick='sendURLToCloudVision("{{ b64 }}")'>Detect Text</a><br>
<textarea name="inscription" id="inscription" cols='70' rows='6'>{{ inscription }}</textarea><br>
<label for="inscription" id="message"></label><br>
<input type="text" name="original" size="60" value="{{ original }}"><br>
<input type="text" name="lat" size="60" value="{{ lat }}"> <br>
<input type="text" name="long" size="60" value="{{ long }}"> <br>
<input type="text" name="licence" size="60" value="{{ licence }}"> <br>
<input type="text" name="import" size="60" value="{{ import }}"> <br>
<input type="submit" value="Import Bench from Flickr">
</form>
{% endif %}
<script src="/js/jquery.3.6.4/jquery-3.6.4.min.js"></script>
<script src="/js/vision/vision.js.php"></script>

{% endblock %}

0 comments on commit a480864

Please sign in to comment.