Add image upload functionality with imgur

This commit is contained in:
Pieter Vander Vennet 2020-06-25 03:39:31 +02:00
parent 6187122294
commit 2acd53d150
21 changed files with 458 additions and 69 deletions

View file

@ -11,6 +11,8 @@ import {Tag, TagsFilter} from "./Logic/TagsFilter";
import {FilteredLayer} from "./Logic/FilteredLayer";
import {ImageCarousel} from "./UI/Image/ImageCarousel";
import {FixedUiElement} from "./UI/FixedUiElement";
import {OsmImageUploadHandler} from "./Logic/OsmImageUploadHandler";
import {UserDetails} from "./Logic/OsmConnection";
export class LayerDefinition {
@ -31,7 +33,7 @@ export class LayerDefinition {
removeTouchingElements: boolean = false;
asLayer(basemap: Basemap, allElements: ElementStorage, changes: Changes):
asLayer(basemap: Basemap, allElements: ElementStorage, changes: Changes, userDetails: UserDetails):
FilteredLayer {
const self = this;
@ -53,9 +55,12 @@ export class LayerDefinition {
}
infoboxes.push(new ImageCarousel(tagsES));
infoboxes.push(new FixedUiElement("<div style='width:750px'></div>"));
infoboxes.push(new OsmImageUploadHandler(
tagsES, userDetails, changes
).getUI());
const qbox = new QuestionPicker(changes.asQuestions(self.questions), tagsES);
infoboxes.push(qbox);

View file

@ -26,8 +26,8 @@ export class CommonTagMappings {
public static osmLink = new TagMappingOptions({
key: "id",
mapping: {
"node/-1": "Over enkele momenten sturen we je punt naar OpenStreetMap"
"node/-1": "<span class='osmlink'>Over enkele momenten sturen we je punt naar OpenStreetMap</span>"
},
template: "<a href='https://osm.org/{id}'> Op OSM</a>"
template: "<span class='osmlink'><a href='https://osm.org/{id}'> Op OSM</a></span>"
})
}

View file

@ -16,7 +16,7 @@ export class Playground extends LayerDefinition {
this.removeContainedElements = true;
this.minzoom = 13;
this.questions = [Quests.nameOf(this.name), Quests.accessNatureReserve];
this.questions = [Quests.nameOf(this.name)];
this.style = this.generateStyleFunction();
this.elementsToShow = [
new TagMappingOptions({

View file

@ -19,7 +19,6 @@ export class ImageSearcher extends UIEventSource<string[]> {
constructor(tags: UIEventSource<any>) {
super([]);
// this.ListenTo(this._embeddedImages);
this._tags = tags;
@ -27,7 +26,8 @@ export class ImageSearcher extends UIEventSource<string[]> {
this._wdItem.addCallback(() => {
// Load the wikidata item, then detect usage on 'commons'
let wikidataId = self._wdItem.data;
if (wikidataId.startsWith("Q")) {
// @ts-ignore
if (wikidataId.startsWith("Q")) {
wikidataId = wikidataId.substr(1);
}
Wikimedia.GetWikiData(parseInt(wikidataId), (wd: Wikidata) => {
@ -44,14 +44,17 @@ export class ImageSearcher extends UIEventSource<string[]> {
this._commons.addCallback(() => {
const commons: string = self._commons.data;
// @ts-ignore
if (commons.startsWith("Category:")) {
Wikimedia.GetCategoryFiles(commons, (images: ImagesInCategory) => {
for (const image of images.images) {
self.AddImage(image.filename);
}
})
} else if (commons.startsWith("File:")) {
self.AddImage(commons);
} else { // @ts-ignore
if (commons.startsWith("File:")) {
self.AddImage(commons);
}
}
});
@ -79,7 +82,7 @@ export class ImageSearcher extends UIEventSource<string[]> {
}
private LoadImages(): void {
if(!this._activated){
if (!this._activated) {
return;
}
const imageTag = this._tags.data.image;
@ -90,6 +93,18 @@ export class ImageSearcher extends UIEventSource<string[]> {
}
}
const image0 = this._tags.data["image:0"];
if (image0 !== undefined) {
this.AddImage(image0);
}
let imageIndex = 1;
let imagei = this._tags.data["image:" + imageIndex];
while (imagei !== undefined) {
this.AddImage(imagei);
imageIndex++;
imagei = this._tags.data["image:" + imageIndex];
}
const wdItem = this._tags.data.wikidata;
if (wdItem !== undefined) {
this._wdItem.setData(wdItem);

66
Logic/Imgur.ts Normal file
View file

@ -0,0 +1,66 @@
import $ from "jquery"
export class Imgur {
static uploadMultiple(
title: string, description: string, blobs: FileList,
handleSuccessfullUpload: ((imageURL: string) => void),
allDone: (() => void),
offset:number = 0) {
if (blobs.length == offset) {
allDone();
return;
}
const blob = blobs.item(offset);
const self = this;
this.uploadImage(title, description, blob,
(imageUrl) => {
handleSuccessfullUpload(imageUrl);
self.uploadMultiple(
title, description, blobs,
handleSuccessfullUpload,
allDone,
offset + 1);
}
);
}
static uploadImage(title: string, description: string, blob,
handleSuccessfullUpload: ((imageURL: string) => void)) {
const apiUrl = 'https://api.imgur.com/3/image';
const apiKey = '7070e7167f0a25a';
var settings = {
async: true,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json',
},
mimeType: 'multipart/form-data',
};
var formData = new FormData();
formData.append('image', blob);
formData.append("title", title);
formData.append("description", description)
// @ts-ignore
settings.data = formData;
// Response contains stringified JSON
// Image URL available at response.data.link
$.ajax(settings).done(function (response) {
response = JSON.parse(response);
handleSuccessfullUpload(response.data.link);
});
}
}

View file

@ -69,6 +69,7 @@ export class OsmConnection {
let data = self.userDetails.data;
data.loggedIn = true;
console.log(userInfo);
data.name = userInfo.getAttribute('display_name');
data.csCount = userInfo.getElementsByTagName("changesets")[0].getAttribute("count");
data.img = userInfo.getElementsByTagName("img")[0].getAttribute("href");

View file

@ -0,0 +1,70 @@
/**
* Helps in uplaoding, by generating the rigth title, decription and by adding the tag to the changeset
*/
import {UIEventSource} from "../UI/UIEventSource";
import {ImageUploadFlow} from "../UI/ImageUploadFlow";
import {Changes} from "./Changes";
import {UserDetails} from "./OsmConnection";
export class OsmImageUploadHandler {
private _tags: UIEventSource<any>;
private _changeHandler: Changes;
private _userdetails: UserDetails;
constructor(tags: UIEventSource<any>,
userdetails: UserDetails,
changeHandler: Changes
) {
if (tags === undefined || userdetails === undefined || changeHandler === undefined) {
throw "Something is undefined"
}
console.log(tags, changeHandler, userdetails)
this._tags = tags;
this._changeHandler = changeHandler;
this._userdetails = userdetails;
}
private generateOptions(license: string) {
console.log(this)
console.log(this._tags, this._changeHandler, this._userdetails)
const tags = this._tags.data;
const title = tags.name ?? "Unknown area";
const description = [
"author:" + this._userdetails.name,
"license:" + license,
"wikidata:" + tags.wikidata,
"osmid:" + tags.id,
"name:" + tags.name
].join("\n");
const changes = this._changeHandler;
return {
title: title,
description: description,
handleURL: function (url) {
let freeIndex = 0;
while (tags["image:" + freeIndex] !== undefined) {
freeIndex++;
}
console.log("Adding image:" + freeIndex, url);
changes.addChange(tags.id, "image:" + freeIndex, url);
},
allDone: function () {
changes.uploadAll(function () {
console.log("Writing changes...")
});
}
}
}
getUI(): ImageUploadFlow {
const self = this;
return new ImageUploadFlow(function (license) {
return self.generateOptions(license)
}
);
}
}

View file

@ -100,6 +100,8 @@ export class Wikimedia {
handleWikidata(wd);
});
}
}

View file

@ -44,5 +44,16 @@ When a map feature is clicked, a popup shows the information, images and questio
The answers given by the user are sent (after a few seconds) to OpenStreetMap directly - if the user is logged in. If not logged in, the user is prompted to do so.
### Searching images
Images are fetched from:
- The OSM `image`, `image:0`, `image:1`, ... tags
- The OSM `wikimedia_commons` tags
- If wikidata is present, the wikidata `P18` (image) claim and, if a commons link is present, the commons images
### Uploading images
Images are uplaoded to imgur, as their API was way easier to handle. The URL is written into the changes
The idea is that one in a while, the images are transfered to wikipedia

92
UI/ImageUploadFlow.ts Normal file
View file

@ -0,0 +1,92 @@
import {UIElement} from "./UIElement";
import {UIEventSource} from "./UIEventSource";
import {UIRadioButton} from "./UIRadioButton";
import {VariableUiElement} from "./VariableUIElement";
import $ from "jquery"
import {Imgur} from "../Logic/Imgur";
export class ImageUploadFlow extends UIElement {
private _licensePicker: UIRadioButton;
private _licenseExplanation: UIElement;
private _isUploading: UIEventSource<number> = new UIEventSource<number>(0)
private _uploadOptions: (license: string) => { title: string; description: string; handleURL: (url: string) => void; allDone: (() => void) };
constructor(uploadOptions: ((license: string) =>
{
title: string,
description: string,
handleURL: ((url: string) => void),
allDone: (() => void)
})
) {
super(undefined);
this._uploadOptions = uploadOptions;
this.ListenTo(this._isUploading);
this._licensePicker = UIRadioButton.FromStrings(
[
"CC-BY-SA",
"CC-BY",
"CC0"
]
);
const licenseExplanations = {
"CC-BY-SA":
"<b>Creative Commonse met naamsvermelding en gelijk delen</b><br/>" +
"Je foto mag door iedereen gratis gebruikt worden, als ze je naam vermelden én ze afgeleide werken met deze licentie en attributie delen.",
"CC-BY":
"<b>Creative Commonse met naamsvermelding</b> <br/>" +
"Je foto mag door iedereen gratis gebruikt worden, als ze je naam vermelden",
"CC0":
"<b>Geen copyright</b><br/> Je foto mag door iedereen voor alles gebruikt worden"
}
this._licenseExplanation = new VariableUiElement(
this._licensePicker.SelectedElementIndex.map((license) => {
return licenseExplanations[license?.value]
})
);
}
protected InnerRender(): string {
if (this._isUploading.data > 0) {
return "<b>Bezig met uploaden, nog " + this._isUploading.data + " foto's te gaan...</b>"
}
return "<b>Foto's toevoegen</b><br/>" +
'Kies een licentie:<br/>' +
this._licensePicker.Render() +
this._licenseExplanation.Render() + "<br/>" +
'<input type="file" accept="image/*" name="picField" id="fileselector-' + this.id + '" size="24" multiple="multiple" alt=""/><br/>'
;
}
InnerUpdate(htmlElement: HTMLElement) {
super.InnerUpdate(htmlElement);
this._licensePicker.Update();
const selector = document.getElementById('fileselector-' + this.id);
const self = this;
if (selector != null) {
selector.onchange = function (event) {
const files = $(this).get(0).files;
self._isUploading.setData(files.length);
const opts = self._uploadOptions(self._licensePicker.SelectedElementIndex.data.value);
Imgur.uploadMultiple(opts.title, opts.description, files,
function (url) {
console.log("File saved at", url);
self._isUploading.setData(self._isUploading.data - 1);
opts.handleURL(url);
},
function () {
console.log("All uploads completed")
opts.allDone();
}
)
}
}
}
}

View file

@ -47,6 +47,7 @@ export abstract class UIElement {
let element = document.getElementById(divId);
element.innerHTML = this.Render();
this.Update();
return this;
}
protected abstract InnerRender(): string;

106
UI/UIRadioButton.ts Normal file
View file

@ -0,0 +1,106 @@
import {UIElement} from "./UIElement";
import {UIEventSource} from "./UIEventSource";
import {FixedUiElement} from "./FixedUiElement";
import $ from "jquery"
export class UIRadioButton extends UIElement {
public readonly SelectedElementIndex: UIEventSource<{ index: number, value: string }>
= new UIEventSource<{ index: number, value: string }>(null);
private readonly _elements: UIEventSource<{ element: UIElement, value: string }[]>
constructor(elements: UIEventSource<{ element: UIElement, value: string }[]>) {
super(elements);
this._elements = elements;
}
static FromStrings(choices: string[]): UIRadioButton {
const wrapped = [];
for (const choice of choices) {
wrapped.push({
element: new FixedUiElement(choice),
value: choice
});
}
return new UIRadioButton(new UIEventSource<{ element: UIElement, value: string }[]>(wrapped))
}
private IdFor(i) {
return 'radio-' + this.id + '-' + i;
}
protected InnerRender(): string {
let body = "";
let i = 0;
for (const el of this._elements.data) {
const uielement = el.element;
const value = el.value;
const htmlElement =
'<input type="radio" id="' + this.IdFor(i) + '" name="radiogroup-' + this.id + '" value="' + value + '">' +
'<label for="' + this.IdFor(i) + '">' + uielement.Render() + '</label>' +
'<br>';
body += htmlElement;
i++;
}
return "<form id='" + this.id + "-form'>" + body + "</form>";
}
InnerUpdate(htmlElement: HTMLElement) {
super.InnerUpdate(htmlElement);
const self = this;
function checkButtons() {
for (let i = 0; i < self._elements.data.length; i++) {
const el = document.getElementById(self.IdFor(i));
// @ts-ignore
if (el.checked) {
var v = {index: i, value: self._elements.data[i].value}
self.SelectedElementIndex.setData(v);
}
}
}
const el = document.getElementById(this.id);
el.addEventListener("change",
function () {
checkButtons();
}
);
if (this.SelectedElementIndex.data == null) {
const el = document.getElementById(this.IdFor(0));
el.checked = true;
checkButtons();
} else {
// We check that what is selected matches the previous rendering
var checked = -1;
var expected = -1
for (let i = 0; i < self._elements.data.length; i++) {
const el = document.getElementById(self.IdFor(i));
// @ts-ignore
if (el.checked) {
checked = i;
}
if (el.value === this.SelectedElementIndex.data.value) {
expected = i;
}
}
if (expected != checked) {
const el = document.getElementById(this.IdFor(expected));
// @ts-ignore
el.checked = true;
}
}
}
}

17
UI/VariableUIElement.ts Normal file
View file

@ -0,0 +1,17 @@
import {UIElement} from "./UIElement";
import {UIEventSource} from "./UIEventSource";
export class VariableUiElement extends UIElement {
private _html: UIEventSource<string>;
constructor(html: UIEventSource<string>) {
super(html);
this._html = html;
}
protected InnerRender(): string {
return this._html.data;
}
}

View file

@ -18,6 +18,9 @@ export class VerticalCombine extends UIElement {
return html;
}
InnerUpdate(htmlElement: HTMLElement) {
for (const element of this._elements){
element.Update();
}
}
Activate() {

View file

@ -235,4 +235,8 @@ body {
.hidden {
display: none;
}
.osmlink{
font-size: xx-small;
}

View file

@ -45,6 +45,8 @@
<!-- 3 dagen eerste protoype -->
<!-- 19 juni: eerste feedbackronde, foto's -->
<!-- 23 juni: wikimedia foto's laden -->
<!-- 24 juni: foto's via imgur -->
<script data-goatcounter="https://pietervdvn.goatcounter.com/count"

View file

@ -13,13 +13,18 @@ import {AddButton} from "./UI/AddButton";
import {Tag} from "./Logic/TagsFilter";
import {FilteredLayer} from "./Logic/FilteredLayer";
import {LayerUpdater} from "./Logic/LayerUpdater";
import {Overpass} from "./Logic/Overpass";
import {LoginDependendMessage} from "./UI/LoginDependendMessage";
let dryRun = false;
// Set to true if testing and changes should NOT be saved
const dryRun = false;
// Overpass.testUrl = "http://127.0.0.1:8080/test.json";
if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
// Set to true if testing and changes should NOT be saved
// dryRun = true;
// If you have a testfile somewhere, enable this to spoof overpass
// This should be hosted independantly, e.g. with `cd assets; webfsd -p 8080` + a CORS plugin to disable cors rules
// Overpass.testUrl = "http://127.0.0.1:8080/test.json";
}
// ----------------- SELECT THE RIGHT QUESTSET -----------------
@ -81,7 +86,7 @@ const flayers: FilteredLayer[] = []
for (const layer of questSetToRender.layers) {
const flayer = layer.asLayer(bm, allElements, changes);
const flayer = layer.asLayer(bm, allElements, changes, osmConnection.userDetails.data);
const addButton = {
name: layer.name,

10
package-lock.json generated
View file

@ -2860,6 +2860,11 @@
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"fs": {
"version": "0.0.1-security",
"resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
"integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ="
},
"fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@ -6422,11 +6427,6 @@
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
"integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho="
},
"wikibase-sdk": {
"version": "7.6.1",
"resolved": "https://registry.npmjs.org/wikibase-sdk/-/wikibase-sdk-7.6.1.tgz",
"integrity": "sha512-FCxreLiyO8csswXMZkivUwypWlEB7kLT/kzpHiB8XYY4Iqy0TO+Rjh12uJL6OeaC+eFB0OKQ9TVpTHj+mnYM8w=="
},
"word-wrap": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",

View file

@ -16,6 +16,7 @@
"license": "MIT",
"dependencies": {
"@splidejs/splide": "^2.4.0",
"fs": "0.0.1-security",
"jquery": "latest",
"leaflet": "^1.6.0",
"osm-auth": "^1.0.2",

View file

@ -6,6 +6,7 @@
</head>
<body>
<div id="maindiv">Hello World</div>
<script src="./test.ts"></script>
</body>
</html>

85
test.ts
View file

@ -1,63 +1,50 @@
import {UIEventSource} from "./UI/UIEventSource";
import {WikimediaImage} from "./UI/Image/WikimediaImage";
import {ImagesInCategory, Wikidata, Wikimedia} from "./Logic/Wikimedia";
import {UIElement} from "./UI/UIElement";
import {SlideShow} from "./UI/SlideShow";
import {ImageSearcher} from "./Logic/ImageSearcher";
import {KnownSet} from "./Layers/KnownSet";
import {Park} from "./Layers/Park";
import {FixedUiElement} from "./UI/FixedUiElement";
import $ from "jquery"
import {Imgur} from "./Logic/Imgur";
import {ImageUploadFlow} from "./UI/ImageUploadFlow";
import {UserDetails} from "./Logic/OsmConnection";
import {UIEventSource} from "./UI/UIEventSource";
import {UIRadioButton} from "./UI/UIRadioButton";
import {UIElement} from "./UI/UIElement";
var tags = {
"name": "Astridpark Brugge",
"wikidata":"Q1234",
"leisure":"park"
}
let properties = {
image: "https://www.designindaba.com/sites/default/files/node/news/21663/buteparkcardiff.jpg",
wikimedia_commons: "File:Boekenkast Sint-Lodewijks.jpg",
wikidata: "Q2763812"};
let tagsES = new UIEventSource<any>(properties);
var userdetails = new UserDetails()
userdetails.loggedIn = true;
userdetails.name = "Pietervdvn";
let searcher = new ImageSearcher(tagsES);
new ImageUploadFlow(
).AttachTo("maindiv") //*/
const uiElements = searcher.map((imageURLS : string[]) => {
const uiElements : UIElement[] = [];
for (const url of imageURLS) {
uiElements.push(ImageSearcher.CreateImageElement(url));
}
return uiElements;
});
new SlideShow(
new FixedUiElement("<b>Afbeeldingen</b>"),
uiElements,
new FixedUiElement("Geen afbeeldingen gevonden...")
).AttachTo("maindiv");
searcher.Activate();
/*
const imageSource = new UIEventSource<string>("https://commons.wikimedia.org/wiki/Special:FilePath/File:Pastoor van Haeckeplantsoen, Brugge (1).JPG?width=1000");
$('document').ready(function () {
$('input[type=file]').on('change', function () {
var $files = $(this).get(0).files;
// new SimpleImageElement(imageSource).AttachTo("maindiv");
const wikimediaImageSource = new UIEventSource<string>("File:Deelboekenkast_rouppeplein.jpg");
// new WikimediaImage(wikimediaImageSource).AttachTo("maindiv");
if ($files.length) {
// Reject big files
if ($files[0].size > $(this).data('max-size') * 1024) {
console.log('Please select a smaller file');
return false;
}
const wdItem = 2763812;
Wikimedia.GetWikiData(wdItem, (wd : Wikidata) => {
// Begin file upload
console.log('Uploading file to Imgur..');
const category = wd.commonsWiki;
Wikimedia.GetCategoryFiles(category, (images: ImagesInCategory) => {
const imageElements: UIElement[] = [];
for (const image of images.images) {
const wikimediaImageSource = new UIEventSource<string>(image.filename);
var uielem = new WikimediaImage(wikimediaImageSource);
imageElements.push(uielem);
const imgur = new Imgur();
imgur.uploadImage("KorenBloem", "Een korenbloem, ergens", $files[0],
(url) => {
console.log("URL: ", url);
})
}
var slides = new UIEventSource<UIElement[]>(imageElements);
new SlideShow(slides).AttachTo("maindiv");
})
})
*/
});
});
*/