'
def has_permission(self, permission: CorpusFollowerPermission):
return self.permissions & permission.value == permission.value
@@ -325,8 +325,8 @@ class CorpusFollowerAssociation(HashidMixin, db.Model):
x.name for x in CorpusFollowerPermission
if self.has_permission(x)
],
- 'followed_corpus': self.followed_corpus.to_json_serializeable(),
- 'following_user': self.following_user.to_json_serializeable()
+ 'corpus': self.corpus.to_json_serializeable(),
+ 'follower': self.follower.to_json_serializeable()
}
return json_serializeable
@@ -368,15 +368,15 @@ class User(HashidMixin, UserMixin, db.Model):
cascade='all, delete-orphan',
lazy='dynamic'
)
- followed_corpus_associations = db.relationship(
+ corpus_follower_associations = db.relationship(
'CorpusFollowerAssociation',
- back_populates='following_user',
+ back_populates='follower',
cascade='all, delete-orphan'
)
followed_corpora = association_proxy(
- 'followed_corpus_associations',
- 'followed_corpus',
- creator=lambda c: CorpusFollowerAssociation(followed_corpus=c)
+ 'corpus_follower_associations',
+ 'corpus',
+ creator=lambda c: CorpusFollowerAssociation(corpus=c)
)
jobs = db.relationship(
'Job',
@@ -652,9 +652,9 @@ class User(HashidMixin, UserMixin, db.Model):
json_serializeable['role'] = \
self.role.to_json_serializeable(backrefs=True)
if relationships:
- json_serializeable['followed_corpus_associations'] = {
+ json_serializeable['corpus_follower_associations'] = {
x.hashid: x.to_json_serializeable()
- for x in self.followed_corpus_associations
+ for x in self.corpus_follower_associations
}
json_serializeable['corpora'] = {
x.hashid: x.to_json_serializeable(relationships=True)
@@ -1319,15 +1319,15 @@ class Corpus(HashidMixin, db.Model):
lazy='dynamic',
cascade='all, delete-orphan'
)
- following_user_associations = db.relationship(
+ corpus_follower_associations = db.relationship(
'CorpusFollowerAssociation',
- back_populates='followed_corpus',
+ back_populates='corpus',
cascade='all, delete-orphan'
)
- following_users = association_proxy(
- 'following_user_associations',
- 'following_user',
- creator=lambda u: CorpusFollowerAssociation(following_user=u)
+ followers = association_proxy(
+ 'corpus_follower_associations',
+ 'follower',
+ creator=lambda u: CorpusFollowerAssociation(followers=u)
)
user = db.relationship('User', back_populates='corpora')
# "static" attributes
@@ -1429,9 +1429,9 @@ class Corpus(HashidMixin, db.Model):
json_serializeable['user'] = \
self.user.to_json_serializeable(backrefs=True)
if relationships:
- json_serializeable['following_user_associations'] = {
+ json_serializeable['corpus_follower_associations'] = {
x.hashid: x.to_json_serializeable()
- for x in self.following_user_associations
+ for x in self.corpus_follower_associations
}
json_serializeable['files'] = {
x.hashid: x.to_json_serializeable(relationships=True)
diff --git a/app/static/js/ResourceLists/CorpusFollowerList.js b/app/static/js/ResourceLists/CorpusFollowerList.js
index 711d5111..d83e4a39 100644
--- a/app/static/js/ResourceLists/CorpusFollowerList.js
+++ b/app/static/js/ResourceLists/CorpusFollowerList.js
@@ -19,7 +19,7 @@ class CorpusFollowerList extends ResourceList {
});
});
app.getUser(this.userId).then((user) => {
- this.add(Object.values(user.corpora[this.corpusId].following_user_associations));
+ this.add(Object.values(user.corpora[this.corpusId].corpus_follower_associations));
this.isInitialized = true;
});
}
@@ -32,20 +32,26 @@ class CorpusFollowerList extends ResourceList {
-
-
- View
-
+
+
+
+ View
+
+
-
-
- Contribute
-
+
+
+
+ Contribute
+
+
-
-
- Administrate
-
+
+
+
+ Administrate
+
+
delete
@@ -95,14 +101,13 @@ class CorpusFollowerList extends ResourceList {
}
mapResourceToValue(corpusFollowerAssociation) {
- let user = corpusFollowerAssociation.following_user;
return {
'id': corpusFollowerAssociation.id,
- 'follower-id': user.id,
- 'avatar': user.avatar ? `/users/${user.id}/avatar` : '/static/images/user_avatar.png',
- 'username': user.username,
- 'full-name': user.full_name ? user.full_name : '',
- 'about-me': user.about_me ? user.about_me : '',
+ 'follower-id': corpusFollowerAssociation.follower.id,
+ 'avatar': corpusFollowerAssociation.follower.avatar ? `/users/${corpusFollowerAssociation.follower.id}/avatar` : '/static/images/user_avatar.png',
+ 'username': corpusFollowerAssociation.follower.username,
+ 'full-name': corpusFollowerAssociation.follower.full_name ? corpusFollowerAssociation.follower.full_name : '',
+ 'about-me': corpusFollowerAssociation.follower.about_me ? corpusFollowerAssociation.follower.about_me : '',
'permission-can-VIEW': corpusFollowerAssociation.permissions.includes('VIEW'),
'permission-can-CONTRIBUTE': corpusFollowerAssociation.permissions.includes('CONTRIBUTE'),
'permission-can-ADMINISTRATE': corpusFollowerAssociation.permissions.includes('ADMINISTRATE')
@@ -141,6 +146,7 @@ class CorpusFollowerList extends ResourceList {
}
onClick(event) {
+ if (event.target.closest('.disable-on-click') !== null) {return;}
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
diff --git a/migrations/versions/03c7211f089d_.py b/migrations/versions/03c7211f089d_.py
new file mode 100644
index 00000000..2f73e3aa
--- /dev/null
+++ b/migrations/versions/03c7211f089d_.py
@@ -0,0 +1,42 @@
+"""empty message
+
+Revision ID: 03c7211f089d
+Revises: 5fe6a6c7870c
+Create Date: 2023-02-21 09:57:22.005883
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '03c7211f089d'
+down_revision = '5fe6a6c7870c'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.alter_column(
+ 'corpus_follower_associations',
+ 'followed_corpus_id',
+ new_column_name='corpus_id'
+ )
+ op.alter_column(
+ 'corpus_follower_associations',
+ 'following_user_id',
+ new_column_name='follower_id'
+ )
+
+
+def downgrade():
+ op.alter_column(
+ 'corpus_follower_associations',
+ 'corpus_id',
+ new_column_name='followed_corpus_id'
+ )
+ op.alter_column(
+ 'corpus_follower_associations',
+ 'follower_id',
+ new_column_name='following_user_id'
+ )
From ff238cd823f559cc246e63364913057a31cf3e6a Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Tue, 21 Feb 2023 11:05:23 +0100
Subject: [PATCH 005/177] Change style of contributionlists
---
.../SpacyNLPPipelineModelList.js | 20 ++++++++-----------
.../TesseractOCRPipelineModelList.js | 15 +++++++-------
2 files changed, 16 insertions(+), 19 deletions(-)
diff --git a/app/static/js/ResourceLists/SpacyNLPPipelineModelList.js b/app/static/js/ResourceLists/SpacyNLPPipelineModelList.js
index b90fb06b..f7901528 100644
--- a/app/static/js/ResourceLists/SpacyNLPPipelineModelList.js
+++ b/app/static/js/ResourceLists/SpacyNLPPipelineModelList.js
@@ -30,14 +30,12 @@ class SpaCyNLPPipelineModelList extends ResourceList {
( )
-
-
+
-
-
- public
+
+ Public
-
+
delete
@@ -80,6 +78,7 @@ class SpaCyNLPPipelineModelList extends ResourceList {
Title and Description
Publisher
+ Availability
@@ -111,6 +110,7 @@ class SpaCyNLPPipelineModelList extends ResourceList {
}
onChange(event) {
+ if (event.target.tagName !== 'INPUT') {return;}
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
@@ -118,7 +118,7 @@ class SpaCyNLPPipelineModelList extends ResourceList {
if (listActionElement === null) {return;}
let listAction = listActionElement.dataset.listAction;
switch (listAction) {
- case 'share-request': {
+ case 'toggle-is-public': {
Utils.spaCyNLPPipelineModelToggleIsPublicRequest(this.userId, itemId);
break;
}
@@ -129,15 +129,11 @@ class SpaCyNLPPipelineModelList extends ResourceList {
}
onClick(event) {
+ if (event.target.closest('.disable-on-click') !== null) {return;}
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
let listActionElement = event.target.closest('.list-action-trigger[data-list-action]');
- // ignore switch clicks, handle them by the onChange method instead
- if (listActionElement.classList.contains('switch')) {
- event.preventDefault();
- this.onChange(event);
- }
let listAction = listActionElement === null ? 'view' : listActionElement.dataset.listAction;
switch (listAction) {
case 'delete-request': {
diff --git a/app/static/js/ResourceLists/TesseractOCRPipelineModelList.js b/app/static/js/ResourceLists/TesseractOCRPipelineModelList.js
index 4ad3f5b1..c5e08b1d 100644
--- a/app/static/js/ResourceLists/TesseractOCRPipelineModelList.js
+++ b/app/static/js/ResourceLists/TesseractOCRPipelineModelList.js
@@ -38,14 +38,12 @@ class TesseractOCRPipelineModelList extends ResourceList {
( )
-
-
+
-
-
- public
+
+ Public
-
+
delete
@@ -89,6 +87,7 @@ class TesseractOCRPipelineModelList extends ResourceList {
Title and Description
Publisher
+ Availability
@@ -120,6 +119,7 @@ class TesseractOCRPipelineModelList extends ResourceList {
}
onChange(event) {
+ if (event.target.tagName !== 'INPUT') {return;}
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
@@ -127,7 +127,7 @@ class TesseractOCRPipelineModelList extends ResourceList {
if (listActionElement === null) {return;}
let listAction = listActionElement.dataset.listAction;
switch (listAction) {
- case 'share-request': {
+ case 'toggle-is-public': {
Utils.tesseractOCRPipelineModelToggleIsPublicRequest(this.userId, itemId);
break;
}
@@ -138,6 +138,7 @@ class TesseractOCRPipelineModelList extends ResourceList {
}
onClick(event) {
+ if (event.target.closest('.disable-on-click') !== null) {return;}
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
From d699fd09e59023eec7d09bc064e332a396aaca99 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Tue, 21 Feb 2023 13:59:11 +0100
Subject: [PATCH 006/177] Add live data updates for corpus follower lists
---
app/models.py | 45 +++++++++++++++----
.../js/ResourceLists/CorpusFollowerList.js | 33 +++++++++++++-
2 files changed, 69 insertions(+), 9 deletions(-)
diff --git a/app/models.py b/app/models.py
index 5e2bdcdf..4e40793b 100644
--- a/app/models.py
+++ b/app/models.py
@@ -653,7 +653,7 @@ class User(HashidMixin, UserMixin, db.Model):
self.role.to_json_serializeable(backrefs=True)
if relationships:
json_serializeable['corpus_follower_associations'] = {
- x.hashid: x.to_json_serializeable()
+ x.hashid: x.to_json_serializeable(relationships=True)
for x in self.corpus_follower_associations
}
json_serializeable['corpora'] = {
@@ -672,10 +672,6 @@ class User(HashidMixin, UserMixin, db.Model):
x.hashid: x.to_json_serializeable(relationships=True)
for x in self.spacy_nlp_pipeline_models
}
- json_serializeable['followed_corpora'] = {
- x.hashid: x.to_json_serializeable(relationships=True)
- for x in self.followed_corpora
- }
if filter_by_privacy_settings:
if not self.has_profile_privacy_setting(ProfilePrivacySettings.SHOW_EMAIL):
@@ -1430,7 +1426,7 @@ class Corpus(HashidMixin, db.Model):
self.user.to_json_serializeable(backrefs=True)
if relationships:
json_serializeable['corpus_follower_associations'] = {
- x.hashid: x.to_json_serializeable()
+ x.hashid: x.to_json_serializeable(relationships=True)
for x in self.corpus_follower_associations
}
json_serializeable['files'] = {
@@ -1454,12 +1450,27 @@ class Corpus(HashidMixin, db.Model):
@db.event.listens_for(TesseractOCRPipelineModel, 'after_delete')
def ressource_after_delete(mapper, connection, ressource):
jsonpatch = [{'op': 'remove', 'path': ressource.jsonpatch_path}]
- room = f'users.{ressource.user_hashid}'
- socketio.emit('users.patch', jsonpatch, room=room)
room = f'/users/{ressource.user_hashid}'
socketio.emit('PATCH', jsonpatch, room=room)
+@db.event.listens_for(CorpusFollowerAssociation, 'after_delete')
+def corpus_follower_association_after_delete_handler(mapper, connection, ressource):
+ corpus_owner_hashid = ressource.corpus.user.hashid
+ corpus_hashid = hashids.encode(ressource.corpus_id)
+ follower_hashid = hashids.encode(ressource.follower_id)
+ # Send a PATCH to the corpus owner
+ jsonpatch_path = f'/users/{corpus_owner_hashid}/corpora/{corpus_hashid}/corpus_follower_associations/{ressource.hashid}'
+ jsonpatch = [{'op': 'remove', 'path': jsonpatch_path}]
+ room = f'/users/{corpus_owner_hashid}'
+ socketio.emit('PATCH', jsonpatch, room=room)
+ # Send a PATCH to the follower
+ jsonpatch_path = f'/users/{follower_hashid}/corpus_follower_associations/{ressource.hashid}'
+ jsonpatch = [{'op': 'remove', 'path': jsonpatch_path}]
+ room = f'/users/{follower_hashid}'
+ socketio.emit('PATCH', jsonpatch, room=room)
+
+
@db.event.listens_for(Corpus, 'after_insert')
@db.event.listens_for(CorpusFile, 'after_insert')
@db.event.listens_for(Job, 'after_insert')
@@ -1478,6 +1489,24 @@ def ressource_after_insert_handler(mapper, connection, ressource):
socketio.emit('PATCH', jsonpatch, room=room)
+# @db.event.listens_for(CorpusFollowerAssociation, 'after_insert')
+# def corpus_follower_association_after_insert_handler(mapper, connection, ressource):
+# corpus_owner_hashid = ressource.corpus.user.hashid
+# corpus_hashid = hashids.encode(ressource.corpus_id)
+# follower_hashid = hashids.encode(ressource.follower_id)
+# value = ressource.to_json_serializeable()
+# # Send a PATCH to the corpus owner
+# jsonpatch_path = f'/users/{corpus_owner_hashid}/corpora/{corpus_hashid}/corpus_follower_associations/{ressource.hashid}'
+# jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
+# room = f'/users/{corpus_owner_hashid}'
+# socketio.emit('PATCH', jsonpatch, room=room)
+# # Send a PATCH to the follower
+# jsonpatch_path = f'/users/{follower_hashid}/corpus_follower_associations/{ressource.hashid}'
+# jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
+# room = f'/users/{follower_hashid}'
+# socketio.emit('PATCH', jsonpatch, room=room)
+
+
@db.event.listens_for(Corpus, 'after_update')
@db.event.listens_for(CorpusFile, 'after_update')
@db.event.listens_for(Job, 'after_update')
diff --git a/app/static/js/ResourceLists/CorpusFollowerList.js b/app/static/js/ResourceLists/CorpusFollowerList.js
index d83e4a39..616f3793 100644
--- a/app/static/js/ResourceLists/CorpusFollowerList.js
+++ b/app/static/js/ResourceLists/CorpusFollowerList.js
@@ -169,5 +169,36 @@ class CorpusFollowerList extends ResourceList {
}
}
- onPatch(patch) {}
+ onPatch(patch) {
+ let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)`);
+ let filteredPatch = patch.filter(operation => re.test(operation.path));
+ for (let operation of filteredPatch) {
+ switch(operation.op) {
+ case 'add': {
+ // let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)$`);
+ // if (re.test(operation.path)) {this.add(operation.value);}
+ break;
+ }
+ case 'remove': {
+ let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)$`);
+ if (re.test(operation.path)) {
+ let [match, jobId] = operation.path.match(re);
+ this.remove(jobId);
+ }
+ break;
+ }
+ case 'replace': {
+ // let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)/(service|status|description|title)$`);
+ // if (re.test(operation.path)) {
+ // let [match, jobId, valueName] = operation.path.match(re);
+ // this.replace(jobId, valueName, operation.value);
+ // }
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+ }
}
From 726e781692f5971e65ed460e6e8d070326c19e9f Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Tue, 21 Feb 2023 16:18:04 +0100
Subject: [PATCH 007/177] share link generator update
---
app/corpora/routes.py | 74 ++++++++++++++++------------
app/static/js/Utils.js | 30 +++++++++++
app/templates/corpora/corpus.html.j2 | 65 +++++++++++++++++-------
3 files changed, 120 insertions(+), 49 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index 8d2dd45f..55de99f3 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import datetime, timedelta
from flask import (
abort,
current_app,
@@ -7,7 +7,8 @@ from flask import (
redirect,
render_template,
request,
- send_from_directory
+ send_from_directory,
+ url_for
)
from flask_login import current_user, login_required
from threading import Thread
@@ -52,22 +53,20 @@ def disable_corpus_is_public(corpus_id):
return '', 204
-# @bp.route('//follow/')
-# @login_required
-# def follow_corpus(corpus_id, token):
-# try:
-# payload = jwt.decode(
-# token,
-# current_app.config['SECRET_KEY'],
-# algorithms=['HS256'],
-# issuer=current_app.config['SERVER_NAME'],
-# options={'require': ['iat', 'iss', 'sub']}
-# )
-# except jwt.PyJWTError:
-# return False
-# corpus_hashid = payload.get('sub')
-# corpus_id = hashids.decode(corpus_hashid)
-# return redirect(url_for('.corpus', corpus_id=corpus_id))
+@bp.route('//follow/')
+@login_required
+def follow_corpus(corpus_id, token):
+ try:
+ payload = jwt.decode(
+ token,
+ current_app.config['SECRET_KEY'],
+ algorithms=['HS256'],
+ issuer=current_app.config['SERVER_NAME'],
+ options={'require': ['iat', 'iss', 'sub']}
+ )
+ except jwt.PyJWTError:
+ return False
+ return redirect(url_for('.corpus', corpus_id=corpus_id))
@bp.route('//unfollow', methods=['GET', 'POST'])
@@ -157,27 +156,16 @@ def create_corpus():
)
-@bp.route('/', methods=['GET', 'POST'])
+@bp.route('/')
@login_required
def corpus(corpus_id):
corpus = Corpus.query.get_or_404(corpus_id)
+ exp_date = (datetime.utcnow() + timedelta(days=7)).strftime('%b %d, %Y')
if corpus.user == current_user or current_user.is_administrator():
- # now = datetime.utcnow()
- # payload = {
- # 'exp': now + timedelta(weeks=1),
- # 'iat': now,
- # 'iss': current_app.config['SERVER_NAME'],
- # 'sub': corpus.hashid
- # }
- # token = jwt.encode(
- # payload,
- # current_app.config['SECRET_KEY'],
- # algorithm='HS256'
- # )
return render_template(
'corpora/corpus.html.j2',
corpus=corpus,
- # token=token,
+ exp_date=exp_date,
title='Corpus'
)
if current_user.is_following_corpus(corpus) or corpus.is_public:
@@ -190,6 +178,28 @@ def corpus(corpus_id):
)
abort(403)
+@bp.route('//generate-corpus-share-link', methods=['GET', 'POST'])
+@login_required
+def generate_corpus_share_link(corpus_id):
+ data = request.get_json('data')
+ permission = data['permission']
+ expiration = data['expiration']
+ corpus = Corpus.query.get_or_404(corpus_id)
+ now = datetime.utcnow()
+ payload = {
+ 'exp': expiration,
+ 'iat': now,
+ 'iss': current_app.config['SERVER_NAME'],
+ 'sub': permission
+ }
+ token = jwt.encode(
+ payload,
+ current_app.config['SECRET_KEY'],
+ algorithm='HS256'
+ )
+ link = url_for('corpora.follow_corpus', corpus_id=corpus_id, token=token, _external=True)
+ return link
+
@bp.route('/', methods=['DELETE'])
@login_required
diff --git a/app/static/js/Utils.js b/app/static/js/Utils.js
index e2ac84ab..b3da4ca1 100644
--- a/app/static/js/Utils.js
+++ b/app/static/js/Utils.js
@@ -751,4 +751,34 @@ class Utils {
);
});
}
+
+ static generateCorpusShareLinkRequest(corpusId, permission, expiration) {
+ return new Promise((resolve, reject) => {
+ const data = {permission: permission, expiration: expiration};
+ fetch(`/corpora/${corpusId}/generate-corpus-share-link`, {method: 'POST', headers: {Accept: 'text/plain'}, body: JSON.stringify(data)})
+ .then(
+ (response) => {
+ if (!response.ok) {
+ app.flash(`Something went wrong: ${response.status} ${response.statusText}`, 'error');
+ reject(response);
+ return;
+ }
+ return response.text();
+ },
+ (response) => {
+ // Something went wrong during the HTTP request
+ app.flash('Something went wrong', 'error');
+ reject(response);
+ }
+ )
+ .then(
+ (corpusShareLink) => {resolve(corpusShareLink);},
+ (error) => {
+ // Something went wrong during ReadableStream processing
+ app.flash('Something went wrong', 'error');
+ reject(error);
+ }
+ );
+ });
+ }
}
diff --git a/app/templates/corpora/corpus.html.j2 b/app/templates/corpora/corpus.html.j2
index 34228347..c84d6c0e 100644
--- a/app/templates/corpora/corpus.html.j2
+++ b/app/templates/corpora/corpus.html.j2
@@ -80,10 +80,13 @@
- {#
+
-
+
Share your Corpus
+
+
+
@@ -91,14 +94,38 @@
public
-
-
Generate Share Link
-
-
Copy
+
+
+
+
+
+
+ View
+ Contribute
+ Administrate
+
+ Permission
+
+
+
+
+
+
+
+ Expiration date
+
+
+
+
-
#}
+
{% endblock page_content %}
@@ -115,19 +142,23 @@
{{ super() }}
-{# #}
+
{% endblock scripts %}
From 68dc8de476446cc6f66c6ce26fb85d6be8f410ab Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Tue, 21 Feb 2023 16:23:10 +0100
Subject: [PATCH 008/177] Add function to dynamically add followers to
CorpusFollowerList
---
app/corpora/routes.py | 10 ++++++
app/models.py | 32 +++++++++----------
.../js/ResourceLists/CorpusFollowerList.js | 4 +--
app/static/js/ResourceLists/ResourceList.js | 3 +-
4 files changed, 30 insertions(+), 19 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index 17d203f1..0b2c788e 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -31,6 +31,16 @@ from .forms import (
)
+@bp.route('/fake-add')
+@login_required
+def fake_add():
+ pjentsch = User.query.filter_by(username='pjentsch').first()
+ alice = Corpus.query.filter_by(title='Alice in Wonderland').first()
+ pjentsch.follow_corpus(alice)
+ db.session.commit()
+ return ''
+
+
@bp.route('//is_public/enable', methods=['POST'])
@login_required
def enable_corpus_is_public(corpus_id):
diff --git a/app/models.py b/app/models.py
index 4e40793b..e2706eb5 100644
--- a/app/models.py
+++ b/app/models.py
@@ -1489,22 +1489,22 @@ def ressource_after_insert_handler(mapper, connection, ressource):
socketio.emit('PATCH', jsonpatch, room=room)
-# @db.event.listens_for(CorpusFollowerAssociation, 'after_insert')
-# def corpus_follower_association_after_insert_handler(mapper, connection, ressource):
-# corpus_owner_hashid = ressource.corpus.user.hashid
-# corpus_hashid = hashids.encode(ressource.corpus_id)
-# follower_hashid = hashids.encode(ressource.follower_id)
-# value = ressource.to_json_serializeable()
-# # Send a PATCH to the corpus owner
-# jsonpatch_path = f'/users/{corpus_owner_hashid}/corpora/{corpus_hashid}/corpus_follower_associations/{ressource.hashid}'
-# jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
-# room = f'/users/{corpus_owner_hashid}'
-# socketio.emit('PATCH', jsonpatch, room=room)
-# # Send a PATCH to the follower
-# jsonpatch_path = f'/users/{follower_hashid}/corpus_follower_associations/{ressource.hashid}'
-# jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
-# room = f'/users/{follower_hashid}'
-# socketio.emit('PATCH', jsonpatch, room=room)
+@db.event.listens_for(CorpusFollowerAssociation, 'after_insert')
+def corpus_follower_association_after_insert_handler(mapper, connection, ressource):
+ corpus_owner_hashid = ressource.corpus.user.hashid
+ corpus_hashid = hashids.encode(ressource.corpus_id)
+ follower_hashid = hashids.encode(ressource.follower_id)
+ value = ressource.to_json_serializeable()
+ # Send a PATCH to the corpus owner
+ jsonpatch_path = f'/users/{corpus_owner_hashid}/corpora/{corpus_hashid}/corpus_follower_associations/{ressource.hashid}'
+ jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
+ room = f'/users/{corpus_owner_hashid}'
+ socketio.emit('PATCH', jsonpatch, room=room)
+ # Send a PATCH to the follower
+ jsonpatch_path = f'/users/{follower_hashid}/corpus_follower_associations/{ressource.hashid}'
+ jsonpatch = [{'op': 'add', 'path': jsonpatch_path, 'value': value}]
+ room = f'/users/{follower_hashid}'
+ socketio.emit('PATCH', jsonpatch, room=room)
@db.event.listens_for(Corpus, 'after_update')
diff --git a/app/static/js/ResourceLists/CorpusFollowerList.js b/app/static/js/ResourceLists/CorpusFollowerList.js
index 616f3793..be7e46d9 100644
--- a/app/static/js/ResourceLists/CorpusFollowerList.js
+++ b/app/static/js/ResourceLists/CorpusFollowerList.js
@@ -175,8 +175,8 @@ class CorpusFollowerList extends ResourceList {
for (let operation of filteredPatch) {
switch(operation.op) {
case 'add': {
- // let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)$`);
- // if (re.test(operation.path)) {this.add(operation.value);}
+ let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)$`);
+ if (re.test(operation.path)) {this.add(operation.value);}
break;
}
case 'remove': {
diff --git a/app/static/js/ResourceLists/ResourceList.js b/app/static/js/ResourceLists/ResourceList.js
index b7445553..3251ef2b 100644
--- a/app/static/js/ResourceLists/ResourceList.js
+++ b/app/static/js/ResourceLists/ResourceList.js
@@ -43,7 +43,8 @@ class ResourceList {
}
add(resources, callback) {
- let values = resources.map((resource) => {
+ let tmp = Array.isArray(resources) ? resources : [resources];
+ let values = tmp.map((resource) => {
return this.mapResourceToValue(resource);
});
this.listjs.add(values, (items) => {
From 1be8a449fea660f7a3a5bd8b4d000f384e32724a Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Wed, 22 Feb 2023 09:35:19 +0100
Subject: [PATCH 009/177] cleanup in models file
---
app/models.py | 59 ++++++++++++++++++++++++++++++++++++++++++++-------
1 file changed, 51 insertions(+), 8 deletions(-)
diff --git a/app/models.py b/app/models.py
index e2706eb5..79ee0ac7 100644
--- a/app/models.py
+++ b/app/models.py
@@ -205,6 +205,8 @@ class Role(HashidMixin, db.Model):
if self.has_permission(x.value)
]
}
+ if backrefs:
+ pass
if relationships:
json_serializeable['users'] = {
x.hashid: x.to_json_serializeable(relationships=True)
@@ -256,6 +258,27 @@ class Token(db.Model):
self.access_expiration = datetime.utcnow()
self.refresh_expiration = datetime.utcnow()
+ def to_json_serializeable(self, backrefs=False, relationships=False):
+ json_serializeable = {
+ 'id': self.hashid,
+ 'access_token': self.access_token,
+ 'access_expiration': (
+ None if self.access_expiration is None
+ else f'{self.access_expiration.isoformat()}Z'
+ ),
+ 'refresh_token': self.refresh_token,
+ 'refresh_expiration': (
+ None if self.refresh_expiration is None
+ else f'{self.refresh_expiration.isoformat()}Z'
+ )
+ }
+ if backrefs:
+ json_serializeable['user'] = \
+ self.user.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
+ return json_serializeable
+
@staticmethod
def clean():
"""Remove any tokens that have been expired for more than a day."""
@@ -288,6 +311,11 @@ class Avatar(HashidMixin, FileMixin, db.Model):
'id': self.hashid,
**self.file_mixin_to_json_serializeable()
}
+ if backrefs:
+ json_serializeable['user'] = \
+ self.user.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -328,6 +356,13 @@ class CorpusFollowerAssociation(HashidMixin, db.Model):
'corpus': self.corpus.to_json_serializeable(),
'follower': self.follower.to_json_serializeable()
}
+ if backrefs:
+ json_serializeable['corpus'] = \
+ self.corpus.to_json_serializeable(backrefs=True)
+ json_serializeable['follower'] = \
+ self.follower.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -620,7 +655,6 @@ class User(HashidMixin, UserMixin, db.Model):
def is_following_corpus(self, corpus):
return corpus in self.followed_corpora
-
def to_json_serializeable(self, backrefs=False, relationships=False, filter_by_privacy_settings=False):
json_serializeable = {
'id': self.hashid,
@@ -628,9 +662,9 @@ class User(HashidMixin, UserMixin, db.Model):
'email': self.email,
'last_seen': (
None if self.last_seen is None
- else self.last_seen.strftime('%Y-%m-%d %H:%M')
+ else f'{self.last_seen.isoformat()}Z'
),
- 'member_since': self.member_since.strftime('%Y-%m-%d'),
+ 'member_since': f'{self.member_since.isoformat()}Z',
'username': self.username,
'full_name': self.full_name,
'about_me': self.about_me,
@@ -804,6 +838,8 @@ class TesseractOCRPipelineModel(FileMixin, HashidMixin, db.Model):
if backrefs:
json_serializeable['user'] = \
self.user.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -930,7 +966,10 @@ class SpaCyNLPPipelineModel(FileMixin, HashidMixin, db.Model):
**self.file_mixin_to_json_serializeable()
}
if backrefs:
- json_serializeable['user'] = self.user.to_json_serializeable(backrefs=True)
+ json_serializeable['user'] = \
+ self.user.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -989,6 +1028,8 @@ class JobInput(FileMixin, HashidMixin, db.Model):
if backrefs:
json_serializeable['job'] = \
self.job.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -1053,6 +1094,8 @@ class JobResult(FileMixin, HashidMixin, db.Model):
if backrefs:
json_serializeable['job'] = \
self.job.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
@@ -1132,7 +1175,6 @@ class Job(HashidMixin, db.Model):
raise e
return job
-
def delete(self):
''' Delete the job and its inputs and results from the database. '''
if self.status not in [JobStatus.COMPLETED, JobStatus.FAILED]: # noqa
@@ -1177,8 +1219,7 @@ class Job(HashidMixin, db.Model):
'service_args': self.service_args,
'service_version': self.service_version,
'status': self.status.name,
- 'title': self.title,
- 'url': self.url
+ 'title': self.title
}
if backrefs:
json_serializeable['user'] = \
@@ -1264,9 +1305,9 @@ class CorpusFile(FileMixin, HashidMixin, db.Model):
def to_json_serializeable(self, backrefs=False, relationships=False):
json_serializeable = {
'id': self.hashid,
- 'url': self.url,
'address': self.address,
'author': self.author,
+ 'description': self.description,
'booktitle': self.booktitle,
'chapter': self.chapter,
'editor': self.editor,
@@ -1285,6 +1326,8 @@ class CorpusFile(FileMixin, HashidMixin, db.Model):
if backrefs:
json_serializeable['corpus'] = \
self.corpus.to_json_serializeable(backrefs=True)
+ if relationships:
+ pass
return json_serializeable
From 3ad942f17b5625a087586f6cb57bd37de1d83b27 Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Wed, 22 Feb 2023 16:00:04 +0100
Subject: [PATCH 010/177] Share link implementation for followers
---
app/corpora/routes.py | 41 ++++++++++++-------
.../js/RessourceDisplays/CorpusDisplay.js | 25 +++++++++++
app/static/js/Utils.js | 6 ++-
app/templates/corpora/corpus.html.j2 | 35 +++-------------
app/templates/corpora/public_corpus.html.j2 | 4 +-
5 files changed, 64 insertions(+), 47 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index be3e7814..b6bedc24 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -57,17 +57,27 @@ def disable_corpus_is_public(corpus_id):
@bp.route('//follow/')
@login_required
def follow_corpus(corpus_id, token):
- try:
+ corpus = Corpus.query.get_or_404(corpus_id)
+ try:
payload = jwt.decode(
- token,
- current_app.config['SECRET_KEY'],
- algorithms=['HS256'],
- issuer=current_app.config['SERVER_NAME'],
- options={'require': ['iat', 'iss', 'sub']}
- )
+ token,
+ current_app.config['SECRET_KEY'],
+ algorithms=['HS256'],
+ issuer=current_app.config['SERVER_NAME'],
+ # options={'require': ['exp', 'iat', 'iss', 'sub']}
+ options={'require': ['exp', 'iat', 'iss']}
+ )
except jwt.PyJWTError:
- return False
- return redirect(url_for('.corpus', corpus_id=corpus_id))
+ abort(403)
+ # permission = payload.get('sub')
+ expiration = payload.get('exp')
+ if expiration < int(datetime.utcnow().timestamp()):
+ abort(403)
+ if not current_user.is_following_corpus(corpus):
+ current_user.follow_corpus(corpus)
+ db.session.commit()
+ flash(f'You are following {corpus.title} now', category='corpus')
+ return redirect(url_for('corpora.corpus', corpus_id=corpus_id))
@bp.route('//followers//unfollow', methods=['POST'])
@@ -170,6 +180,9 @@ def create_corpus():
def corpus(corpus_id):
corpus = Corpus.query.get_or_404(corpus_id)
exp_date = (datetime.utcnow() + timedelta(days=7)).strftime('%b %d, %Y')
+ print(corpus.user)
+ print(current_user)
+ print(current_user.is_following_corpus(corpus))
if corpus.user == current_user or current_user.is_administrator():
return render_template(
'corpora/corpus.html.j2',
@@ -191,15 +204,15 @@ def corpus(corpus_id):
@login_required
def generate_corpus_share_link(corpus_id):
data = request.get_json('data')
- permission = data['permission']
- expiration = data['expiration']
- corpus = Corpus.query.get_or_404(corpus_id)
+ # permission = data['permission']
+ exp_data = data['expiration']
+ expiration = datetime.strptime(exp_data, '%b %d, %Y')
now = datetime.utcnow()
payload = {
'exp': expiration,
'iat': now,
- 'iss': current_app.config['SERVER_NAME'],
- 'sub': permission
+ 'iss': current_app.config['SERVER_NAME']
+ # 'sub': permission
}
token = jwt.encode(
payload,
diff --git a/app/static/js/RessourceDisplays/CorpusDisplay.js b/app/static/js/RessourceDisplays/CorpusDisplay.js
index fd342dd4..aab9e470 100644
--- a/app/static/js/RessourceDisplays/CorpusDisplay.js
+++ b/app/static/js/RessourceDisplays/CorpusDisplay.js
@@ -31,6 +31,7 @@ class CorpusDisplay extends RessourceDisplay {
this.setStatus(corpus.status);
this.setTitle(corpus.title);
this.setNumTokens(corpus.num_tokens);
+ this.setShareLink();
}
onPatch(patch) {
@@ -117,4 +118,28 @@ class CorpusDisplay extends RessourceDisplay {
new Date(creationDate).toLocaleString("en-US")
);
}
+
+ setShareLink() {
+ let generateShareLinkButton = this.displayElement.querySelector('#generate-share-link-button');
+ let copyShareLinkButton = this.displayElement.querySelector('#copy-share-link-button');
+ let shareLinkInput = this.displayElement.querySelector('#share-link-input');
+ // let permissionSelect = this.displayElement.querySelector('#permission-select');
+ let expirationDate = this.displayElement.querySelector('#expiration');
+
+
+ generateShareLinkButton.addEventListener('click', () => {
+ // Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, permissionSelect.value, expirationDate.value)
+ Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, expirationDate.value)
+ .then((shareLink) => {
+ shareLinkInput.parentElement.classList.remove('hide');
+ shareLinkInput.value = shareLink;
+ });
+ });
+
+ copyShareLinkButton.addEventListener('click', () => {
+ shareLinkInput.select();
+ navigator.clipboard.writeText(shareLinkInput.value);
+ app.flash(`Copied!`, 'success');
+ });
+ }
}
diff --git a/app/static/js/Utils.js b/app/static/js/Utils.js
index 80340d6c..354f0f63 100644
--- a/app/static/js/Utils.js
+++ b/app/static/js/Utils.js
@@ -778,9 +778,11 @@ class Utils {
});
}
- static generateCorpusShareLinkRequest(corpusId, permission, expiration) {
+ // static generateCorpusShareLinkRequest(corpusId, permission, expiration) {
+ static generateCorpusShareLinkRequest(corpusId, expiration) {
return new Promise((resolve, reject) => {
- const data = {permission: permission, expiration: expiration};
+ // const data = {permission: permission, expiration: expiration};
+ const data = {expiration: expiration};
fetch(`/corpora/${corpusId}/generate-corpus-share-link`, {method: 'POST', headers: {Accept: 'text/plain'}, body: JSON.stringify(data)})
.then(
(response) => {
diff --git a/app/templates/corpora/corpus.html.j2 b/app/templates/corpora/corpus.html.j2
index 0e982d70..8a4976e2 100644
--- a/app/templates/corpora/corpus.html.j2
+++ b/app/templates/corpora/corpus.html.j2
@@ -96,7 +96,7 @@
-
+ {#
@@ -107,7 +107,7 @@
Permission
-
+
#}
@@ -142,30 +144,5 @@
{{ super() }}
{% endblock scripts %}
diff --git a/app/templates/corpora/public_corpus.html.j2 b/app/templates/corpora/public_corpus.html.j2
index 94b3524c..63744441 100644
--- a/app/templates/corpora/public_corpus.html.j2
+++ b/app/templates/corpora/public_corpus.html.j2
@@ -61,13 +61,13 @@
let unfollowRequestElement = document.querySelector('.action-button[data-action="unfollow-request"]');
unfollowRequestElement.addEventListener('click', () => {
return new Promise((resolve, reject) => {
- fetch('{{ url_for("corpora.unfollow_corpus", corpus_id=corpus.id) }}', {method: 'POST', headers: {Accept: 'application/json'}})
+ fetch('{{ url_for("corpora.current_user_unfollow_corpus", corpus_id=corpus.id) }}', {method: 'POST', headers: {Accept: 'application/json'}})
.then(
(response) => {
if (response.status === 403) {app.flash('Forbidden', 'error'); reject(response);}
if (response.status === 404) {app.flash('Not Found', 'error'); reject(response);}
resolve(response);
- window.location.href = '{{ url_for("corpora.corpus", corpus_id=corpus.id) }}';
+ window.location.href = '{{ url_for("main.dashboard") }}';
},
(response) => {
app.flash('Something went wrong', 'error');
From a459d6607a4f41db0fe29a6617f60b148bdce36a Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Thu, 23 Feb 2023 09:50:09 +0100
Subject: [PATCH 011/177] Update Share Link
---
app/corpora/routes.py | 5 +----
app/static/js/RessourceDisplays/CorpusDisplay.js | 3 ++-
app/templates/corpora/corpus.html.j2 | 14 +++++++++++---
3 files changed, 14 insertions(+), 8 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index ab07ca92..9341938a 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -78,11 +78,8 @@ def follow_corpus(corpus_id, token):
options={'require': ['exp', 'iat', 'iss']}
)
except jwt.PyJWTError:
- abort(403)
+ abort(410)
# permission = payload.get('sub')
- expiration = payload.get('exp')
- if expiration < int(datetime.utcnow().timestamp()):
- abort(403)
if not current_user.is_following_corpus(corpus):
current_user.follow_corpus(corpus)
db.session.commit()
diff --git a/app/static/js/RessourceDisplays/CorpusDisplay.js b/app/static/js/RessourceDisplays/CorpusDisplay.js
index aab9e470..d42fa20c 100644
--- a/app/static/js/RessourceDisplays/CorpusDisplay.js
+++ b/app/static/js/RessourceDisplays/CorpusDisplay.js
@@ -123,6 +123,7 @@ class CorpusDisplay extends RessourceDisplay {
let generateShareLinkButton = this.displayElement.querySelector('#generate-share-link-button');
let copyShareLinkButton = this.displayElement.querySelector('#copy-share-link-button');
let shareLinkInput = this.displayElement.querySelector('#share-link-input');
+ let shareLinkContainer = this.displayElement.querySelector('#share-link-container');
// let permissionSelect = this.displayElement.querySelector('#permission-select');
let expirationDate = this.displayElement.querySelector('#expiration');
@@ -131,7 +132,7 @@ class CorpusDisplay extends RessourceDisplay {
// Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, permissionSelect.value, expirationDate.value)
Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, expirationDate.value)
.then((shareLink) => {
- shareLinkInput.parentElement.classList.remove('hide');
+ shareLinkContainer.classList.remove('hide');
shareLinkInput.value = shareLink;
});
});
diff --git a/app/templates/corpora/corpus.html.j2 b/app/templates/corpora/corpus.html.j2
index 8a4976e2..196faef2 100644
--- a/app/templates/corpora/corpus.html.j2
+++ b/app/templates/corpora/corpus.html.j2
@@ -119,9 +119,17 @@
From 38d09a34904f1b323ecb4f5c9ded23674f448ad4 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Thu, 23 Feb 2023 13:05:04 +0100
Subject: [PATCH 012/177] Integrate CorpusFollowerRoles
---
app/cli.py | 17 +-
app/corpora/routes.py | 29 +--
app/models.py | 191 ++++++++++++++----
.../js/ResourceLists/CorpusFollowerList.js | 84 ++++----
app/templates/_sidenav.html.j2 | 6 +-
migrations/versions/1f77ce4346c6_.py | 72 +++++++
nopaque.py | 11 +-
7 files changed, 284 insertions(+), 126 deletions(-)
create mode 100644 migrations/versions/1f77ce4346c6_.py
diff --git a/app/cli.py b/app/cli.py
index 826aa790..e59a080d 100644
--- a/app/cli.py
+++ b/app/cli.py
@@ -3,10 +3,11 @@ from flask_migrate import upgrade
import click
import os
from app.models import (
+ CorpusFollowerRole,
Role,
- User,
+ SpaCyNLPPipelineModel,
TesseractOCRPipelineModel,
- SpaCyNLPPipelineModel
+ User
)
@@ -30,19 +31,23 @@ def register(app):
def deploy():
''' Run deployment tasks. '''
# Make default directories
+ print('Make default directories')
_make_default_dirs()
# migrate database to latest revision
+ print('Migrate database to latest revision')
upgrade()
# Insert/Update default database values
- current_app.logger.info('Insert/Update default roles')
+ print('Insert/Update default Roles')
Role.insert_defaults()
- current_app.logger.info('Insert/Update default users')
+ print('Insert/Update default Users')
User.insert_defaults()
- current_app.logger.info('Insert/Update default SpaCyNLPPipelineModels')
+ print('Insert/Update default CorpusFollowerRoles')
+ CorpusFollowerRole.insert_defaults()
+ print('Insert/Update default SpaCyNLPPipelineModels')
SpaCyNLPPipelineModel.insert_defaults()
- current_app.logger.info('Insert/Update default TesseractOCRPipelineModels')
+ print('Insert/Update default TesseractOCRPipelineModels')
TesseractOCRPipelineModel.insert_defaults()
@app.cli.group()
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index 2d59426b..ecfc1e84 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -21,6 +21,7 @@ from app.models import (
CorpusFile,
CorpusFollowerAssociation,
CorpusFollowerPermission,
+ CorpusFollowerRole,
CorpusStatus,
User
)
@@ -107,30 +108,16 @@ def current_user_unfollow_corpus(corpus_id):
return '', 204
-@bp.route('//followers//permissions//add', methods=['POST'])
-def add_permission(corpus_id, follower_id, permission_name):
- try:
- permission = CorpusFollowerPermission[permission_name]
- except KeyError:
- abort(409) # f'Permission "{permission_name}" does not exist'
+@bp.route('//followers//role', methods=['POST'])
+def add_permission(corpus_id, follower_id):
corpus_follower_association = CorpusFollowerAssociation.query.filter_by(corpus_id=corpus_id, follower_id=follower_id).first_or_404()
if not (corpus_follower_association.corpus.user == current_user or current_user.is_administrator()):
abort(403)
- corpus_follower_association.add_permission(permission)
- db.session.commit()
- return '', 204
-
-
-@bp.route('//followers//permissions//remove', methods=['POST'])
-def remove_permission(corpus_id, follower_id, permission_name):
- try:
- permission = CorpusFollowerPermission[permission_name]
- except KeyError:
- return make_response(f'Permission "{permission_name}" does not exist', 409)
- corpus_follower_association = CorpusFollowerAssociation.query.filter_by(corpus_id=corpus_id, follower_id=follower_id).first_or_404()
- if not (corpus_follower_association.corpus.user == current_user or current_user.is_administrator()):
- abort(403)
- corpus_follower_association.remove_permission(permission)
+ role_name = request.json.get('role')
+ if role_name is None:
+ abort(400)
+ corpus_follower_role = CorpusFollowerRole.query.filter_by(name=role_name).first_or_404()
+ corpus_follower_association.role = corpus_follower_role
db.session.commit()
return '', 204
diff --git a/app/models.py b/app/models.py
index 79ee0ac7..2444589c 100644
--- a/app/models.py
+++ b/app/models.py
@@ -6,6 +6,7 @@ from flask_login import UserMixin
from sqlalchemy.ext.associationproxy import association_proxy
from time import sleep
from tqdm import tqdm
+from typing import Union
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import json
@@ -57,6 +58,15 @@ class Permission(IntEnum):
CONTRIBUTE = 2
USE_API = 4
+ @staticmethod
+ def get(permission: Union['Permission', int, str]) -> 'Permission':
+ if isinstance(permission, Permission):
+ return permission
+ if isinstance(permission, int):
+ return Permission(permission)
+ if isinstance(permission, str):
+ return Permission[permission]
+ raise TypeError('permission must be Permission, int, or str')
class UserSettingJobStatusMailNotificationLevel(IntEnum):
NONE = 1
@@ -72,8 +82,22 @@ class ProfilePrivacySettings(IntEnum):
class CorpusFollowerPermission(IntEnum):
VIEW = 1
- CONTRIBUTE = 2
- ADMINISTRATE = 4
+ ADD_CORPUS_FILE = 2
+ UPDATE_CORPUS_FILE = 4
+ REMOVE_CORPUS_FILE = 8
+ GENERATE_SHARE_LINK = 16
+ REMOVE_FOLLOWER = 32
+ UPDATE_FOLLOWER = 64
+
+ @staticmethod
+ def get(permission: Union['CorpusFollowerPermission', int, str]) -> 'CorpusFollowerPermission':
+ if isinstance(permission, CorpusFollowerPermission):
+ return permission
+ if isinstance(permission, int):
+ return CorpusFollowerPermission(permission)
+ if isinstance(permission, str):
+ return CorpusFollowerPermission[permission]
+ raise TypeError('permission must be CorpusFollowerPermission, int, or str')
# endregion enums
@@ -181,16 +205,19 @@ class Role(HashidMixin, db.Model):
def __repr__(self):
return f''
- def add_permission(self, permission):
- if not self.has_permission(permission):
- self.permissions += permission
-
- def has_permission(self, permission):
- return self.permissions & permission == permission
-
- def remove_permission(self, permission):
- if self.has_permission(permission):
- self.permissions -= permission
+ def has_permission(self, permission: Union[Permission, int, str]):
+ perm = Permission.get(permission)
+ return self.permissions & perm.value == perm.value
+
+ def add_permission(self, permission: Union[Permission, int, str]):
+ perm = Permission.get(permission)
+ if not self.has_permission(perm):
+ self.permissions += perm.value
+
+ def remove_permission(self, permission: Union[Permission, int, str]):
+ perm = Permission.get(permission)
+ if self.has_permission(perm):
+ self.permissions -= perm.value
def reset_permissions(self):
self.permissions = 0
@@ -319,6 +346,96 @@ class Avatar(HashidMixin, FileMixin, db.Model):
return json_serializeable
+class CorpusFollowerRole(HashidMixin, db.Model):
+ __tablename__ = 'corpus_follower_roles'
+ # Primary key
+ id = db.Column(db.Integer, primary_key=True)
+ # Fields
+ name = db.Column(db.String(64), unique=True)
+ default = db.Column(db.Boolean, default=False, index=True)
+ permissions = db.Column(db.Integer, default=0)
+ # Relationships
+ corpus_follower_associations = db.relationship(
+ 'CorpusFollowerAssociation',
+ back_populates='role',
+ lazy='dynamic'
+ )
+
+ def __repr__(self):
+ return f''
+
+ def has_permission(self, permission: Union[CorpusFollowerPermission, int, str]):
+ perm = CorpusFollowerPermission.get(permission)
+ return self.permissions & perm.value == perm.value
+
+ def add_permission(self, permission: Union[CorpusFollowerPermission, int, str]):
+ perm = CorpusFollowerPermission.get(permission)
+ if not self.has_permission(perm):
+ self.permissions += perm.value
+
+ def remove_permission(self, permission: Union[CorpusFollowerPermission, int, str]):
+ perm = CorpusFollowerPermission.get(permission)
+ if self.has_permission(perm):
+ self.permissions -= perm.value
+
+ def reset_permissions(self):
+ self.permissions = 0
+
+ def to_json_serializeable(self, backrefs=False, relationships=False):
+ json_serializeable = {
+ 'id': self.hashid,
+ 'default': self.default,
+ 'name': self.name,
+ 'permissions': [
+ x.name
+ for x in CorpusFollowerPermission
+ if self.has_permission(x)
+ ]
+ }
+ if backrefs:
+ pass
+ if relationships:
+ json_serializeable['corpus_follower_association'] = {
+ x.hashid: x.to_json_serializeable(relationships=True)
+ for x in self.corpus_follower_association
+ }
+ return json_serializeable
+
+ @staticmethod
+ def insert_defaults():
+ roles = {
+ 'Viewer': [
+ CorpusFollowerPermission.VIEW
+ ],
+ 'Contributor': [
+ CorpusFollowerPermission.VIEW,
+ CorpusFollowerPermission.ADD_CORPUS_FILE,
+ CorpusFollowerPermission.UPDATE_CORPUS_FILE,
+ CorpusFollowerPermission.REMOVE_CORPUS_FILE
+ ],
+ 'Administrator': [
+ CorpusFollowerPermission.VIEW,
+ CorpusFollowerPermission.ADD_CORPUS_FILE,
+ CorpusFollowerPermission.UPDATE_CORPUS_FILE,
+ CorpusFollowerPermission.REMOVE_CORPUS_FILE,
+ CorpusFollowerPermission.GENERATE_SHARE_LINK,
+ CorpusFollowerPermission.REMOVE_FOLLOWER,
+ CorpusFollowerPermission.UPDATE_FOLLOWER
+ ]
+ }
+ default_role_name = 'Viewer'
+ for role_name, permissions in roles.items():
+ role = CorpusFollowerRole.query.filter_by(name=role_name).first()
+ if role is None:
+ role = CorpusFollowerRole(name=role_name)
+ role.reset_permissions()
+ for permission in permissions:
+ role.add_permission(permission)
+ role.default = role.name == default_role_name
+ db.session.add(role)
+ db.session.commit()
+
+
class CorpusFollowerAssociation(HashidMixin, db.Model):
__tablename__ = 'corpus_follower_associations'
# Primary key
@@ -326,41 +443,38 @@ class CorpusFollowerAssociation(HashidMixin, db.Model):
# Foreign keys
corpus_id = db.Column(db.Integer, db.ForeignKey('corpora.id'))
follower_id = db.Column(db.Integer, db.ForeignKey('users.id'))
- # Fields
- permissions = db.Column(db.Integer, default=0, nullable=False)
+ role_id = db.Column(db.Integer, db.ForeignKey('corpus_follower_roles.id'))
# Relationships
- corpus = db.relationship('Corpus', back_populates='corpus_follower_associations')
- follower = db.relationship('User', back_populates='corpus_follower_associations')
+ corpus = db.relationship(
+ 'Corpus',
+ back_populates='corpus_follower_associations'
+ )
+ follower = db.relationship(
+ 'User',
+ back_populates='corpus_follower_associations'
+ )
+ role = db.relationship(
+ 'CorpusFollowerRole',
+ back_populates='corpus_follower_associations'
+ )
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ if self.role is None:
+ self.role = CorpusFollowerRole.query.filter_by(default=True).first()
def __repr__(self):
return f''
- def has_permission(self, permission: CorpusFollowerPermission):
- return self.permissions & permission.value == permission.value
-
- def add_permission(self, permission: CorpusFollowerPermission):
- if not self.has_permission(permission):
- self.permissions += permission.value
-
- def remove_permission(self, permission: CorpusFollowerPermission):
- if self.has_permission(permission):
- self.permissions -= permission.value
-
def to_json_serializeable(self, backrefs=False, relationships=False):
json_serializeable = {
'id': self.hashid,
- 'permissions': [
- x.name for x in CorpusFollowerPermission
- if self.has_permission(x)
- ],
'corpus': self.corpus.to_json_serializeable(),
- 'follower': self.follower.to_json_serializeable()
+ 'follower': self.follower.to_json_serializeable(),
+ 'role': self.role.to_json_serializeable()
}
if backrefs:
- json_serializeable['corpus'] = \
- self.corpus.to_json_serializeable(backrefs=True)
- json_serializeable['follower'] = \
- self.follower.to_json_serializeable(backrefs=True)
+ pass
if relationships:
pass
return json_serializeable
@@ -559,7 +673,6 @@ class User(HashidMixin, UserMixin, db.Model):
issuer=current_app.config['SERVER_NAME'],
options={'require': ['exp', 'iat', 'iss', 'purpose', 'sub']}
)
- current_app.logger.warning(payload)
except jwt.PyJWTError:
return False
if payload.get('purpose') != 'user.confirm':
@@ -687,7 +800,7 @@ class User(HashidMixin, UserMixin, db.Model):
self.role.to_json_serializeable(backrefs=True)
if relationships:
json_serializeable['corpus_follower_associations'] = {
- x.hashid: x.to_json_serializeable(relationships=True)
+ x.hashid: x.to_json_serializeable()
for x in self.corpus_follower_associations
}
json_serializeable['corpora'] = {
@@ -1469,7 +1582,7 @@ class Corpus(HashidMixin, db.Model):
self.user.to_json_serializeable(backrefs=True)
if relationships:
json_serializeable['corpus_follower_associations'] = {
- x.hashid: x.to_json_serializeable(relationships=True)
+ x.hashid: x.to_json_serializeable()
for x in self.corpus_follower_associations
}
json_serializeable['files'] = {
diff --git a/app/static/js/ResourceLists/CorpusFollowerList.js b/app/static/js/ResourceLists/CorpusFollowerList.js
index be7e46d9..cc94c568 100644
--- a/app/static/js/ResourceLists/CorpusFollowerList.js
+++ b/app/static/js/ResourceLists/CorpusFollowerList.js
@@ -7,6 +7,9 @@ class CorpusFollowerList extends ResourceList {
constructor(listContainerElement, options = {}) {
super(listContainerElement, options);
+ this.listjs.on('updated', () => {
+ M.FormSelect.init(this.listjs.list.querySelectorAll('.list-item select'));
+ });
this.listjs.list.addEventListener('change', (event) => {this.onChange(event)});
this.listjs.list.addEventListener('click', (event) => {this.onClick(event)});
this.isInitialized = false;
@@ -28,30 +31,21 @@ class CorpusFollowerList extends ResourceList {
return (values) => {
return `
-
-
-
+
+
-
-
-
- View
-
-
+
-
-
-
- Contribute
-
-
-
-
-
-
- Administrate
-
-
+
+
+
+
+
+ Viewer
+ Contributor
+ Administrator
+
+
delete
@@ -66,10 +60,10 @@ class CorpusFollowerList extends ResourceList {
return [
{data: ['id']},
{data: ['follower-id']},
- {name: 'avatar', attr: 'src'},
- 'username',
- 'about-me',
- 'full-name'
+ {name: 'follower-avatar', attr: 'src'},
+ 'follower-username',
+ 'follower-about-me',
+ 'follower-full-name'
];
}
@@ -90,7 +84,7 @@ class CorpusFollowerList extends ResourceList {
Username
User details
- Permissions
+ Role
@@ -104,13 +98,11 @@ class CorpusFollowerList extends ResourceList {
return {
'id': corpusFollowerAssociation.id,
'follower-id': corpusFollowerAssociation.follower.id,
- 'avatar': corpusFollowerAssociation.follower.avatar ? `/users/${corpusFollowerAssociation.follower.id}/avatar` : '/static/images/user_avatar.png',
- 'username': corpusFollowerAssociation.follower.username,
- 'full-name': corpusFollowerAssociation.follower.full_name ? corpusFollowerAssociation.follower.full_name : '',
- 'about-me': corpusFollowerAssociation.follower.about_me ? corpusFollowerAssociation.follower.about_me : '',
- 'permission-can-VIEW': corpusFollowerAssociation.permissions.includes('VIEW'),
- 'permission-can-CONTRIBUTE': corpusFollowerAssociation.permissions.includes('CONTRIBUTE'),
- 'permission-can-ADMINISTRATE': corpusFollowerAssociation.permissions.includes('ADMINISTRATE')
+ 'follower-avatar': corpusFollowerAssociation.follower.avatar ? `/users/${corpusFollowerAssociation.follower.id}/avatar` : '/static/images/user_avatar.png',
+ 'follower-username': corpusFollowerAssociation.follower.username,
+ 'follower-full-name': corpusFollowerAssociation.follower.full_name ? corpusFollowerAssociation.follower.full_name : '',
+ 'follower-about-me': corpusFollowerAssociation.follower.about_me ? corpusFollowerAssociation.follower.about_me : '',
+ 'role-name': corpusFollowerAssociation.role.name
};
}
@@ -119,7 +111,7 @@ class CorpusFollowerList extends ResourceList {
}
onChange(event) {
- if (event.target.tagName !== 'INPUT') {return;}
+ console.log(event.target.tagName);
let listItemElement = event.target.closest('.list-item[data-id]');
if (listItemElement === null) {return;}
let itemId = listItemElement.dataset.id;
@@ -127,16 +119,10 @@ class CorpusFollowerList extends ResourceList {
if (listActionElement === null) {return;}
let listAction = listActionElement.dataset.listAction;
switch (listAction) {
- case 'toggle-permission': {
+ case 'update-role': {
let followerId = listItemElement.dataset.followerId;
- let permission = listActionElement.dataset.permission;
- if (event.target.checked) {
- Utils.addCorpusFollowerPermissionRequest(this.corpusId, followerId, permission)
- .catch((error) => {event.target.checked = !event.target.checked;});
- } else {
- Utils.removeCorpusFollowerPermissionRequest(this.corpusId, followerId, permission)
- .catch((error) => {event.target.checked = !event.target.checked;});
- }
+ let roleName = event.target.value;
+ Utils.updateCorpusFollowerRole(this.corpusId, followerId, roleName);
break;
}
default: {
@@ -188,11 +174,11 @@ class CorpusFollowerList extends ResourceList {
break;
}
case 'replace': {
- // let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)/(service|status|description|title)$`);
- // if (re.test(operation.path)) {
- // let [match, jobId, valueName] = operation.path.match(re);
- // this.replace(jobId, valueName, operation.value);
- // }
+ let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)/role$`);
+ if (re.test(operation.path)) {
+ let [match, jobId, valueName] = operation.path.match(re);
+ this.replace(jobId, valueName, operation.value);
+ }
break;
}
default: {
diff --git a/app/templates/_sidenav.html.j2 b/app/templates/_sidenav.html.j2
index 676b7069..7fa34623 100644
--- a/app/templates/_sidenav.html.j2
+++ b/app/templates/_sidenav.html.j2
@@ -36,13 +36,13 @@
settings General Settings
contact_page Profile settings
Log out
- {% if current_user.can(Permission.ADMINISTRATE) or current_user.can(Permission.USE_API) %}
+ {% if current_user.can('ADMINISTRATE') or current_user.can('USE_API') %}
{% endif %}
- {% if current_user.can(Permission.ADMINISTRATE) %}
+ {% if current_user.can('ADMINISTRATE') %}
admin_panel_settings Administration
{% endif %}
- {% if current_user.can(Permission.USE_API) %}
+ {% if current_user.can('USE_API') %}
api API
{% endif %}
diff --git a/migrations/versions/1f77ce4346c6_.py b/migrations/versions/1f77ce4346c6_.py
new file mode 100644
index 00000000..1d7e2160
--- /dev/null
+++ b/migrations/versions/1f77ce4346c6_.py
@@ -0,0 +1,72 @@
+"""empty message
+
+Revision ID: 1f77ce4346c6
+Revises: 03c7211f089d
+Create Date: 2023-02-22 12:56:30.176665
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '1f77ce4346c6'
+down_revision = '03c7211f089d'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ 'corpus_follower_roles',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('name', sa.String(length=64), nullable=True),
+ sa.Column('default', sa.Boolean(), nullable=True),
+ sa.Column('permissions', sa.Integer(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('name')
+ )
+ op.create_index(
+ op.f('ix_corpus_follower_roles_default'),
+ 'corpus_follower_roles',
+ ['default'],
+ unique=False
+ )
+
+ op.add_column(
+ 'corpus_follower_associations',
+ sa.Column('role_id', sa.Integer(), nullable=True)
+ )
+ op.create_foreign_key(
+ 'fk_corpus_follower_associations_role_id_corpus_follower_roles',
+ 'corpus_follower_associations',
+ 'corpus_follower_roles',
+ ['role_id'],
+ ['id']
+ )
+ op.drop_column('corpus_follower_associations', 'permissions')
+
+
+def downgrade():
+ op.add_column(
+ 'corpus_follower_associations',
+ sa.Column('permissions', sa.Integer(), nullable=True)
+ )
+ op.execute('UPDATE corpus_follower_associations SET permissions = 0;')
+ op.alter_column(
+ 'corpus_follower_associations',
+ 'permissions',
+ nullable=False
+ )
+ op.drop_constraint(
+ 'fk_corpus_follower_associations_role_id_corpus_follower_roles',
+ 'corpus_follower_associations',
+ type_='foreignkey'
+ )
+ op.drop_column('corpus_follower_associations', 'role_id')
+
+ op.drop_index(
+ op.f('ix_corpus_follower_roles_default'),
+ table_name='corpus_follower_roles'
+ )
+ op.drop_table('corpus_follower_roles')
diff --git a/nopaque.py b/nopaque.py
index 602954cc..bbcf799d 100644
--- a/nopaque.py
+++ b/nopaque.py
@@ -9,6 +9,7 @@ from app.models import (
Corpus,
CorpusFile,
CorpusFollowerAssociation,
+ CorpusFollowerRole,
Job,
JobInput,
JobResult,
@@ -26,25 +27,19 @@ app: Flask = create_app()
cli.register(app)
-@app.context_processor
-def make_context() -> Dict[str, Any]:
- ''' Adds variables to the template context. '''
- return {'Permission': Permission}
-
-
@app.shell_context_processor
def make_shell_context() -> Dict[str, Any]:
''' Adds variables to the shell context. '''
return {
+ 'db': db,
'Avatar': Avatar,
'Corpus': Corpus,
'CorpusFile': CorpusFile,
'CorpusFollowerAssociation': CorpusFollowerAssociation,
- 'db': db,
+ 'CorpusFollowerRole': CorpusFollowerRole,
'Job': Job,
'JobInput': JobInput,
'JobResult': JobResult,
- 'Permission': Permission,
'Role': Role,
'TesseractOCRPipelineModel': TesseractOCRPipelineModel,
'SpaCyNLPPipelineModel': SpaCyNLPPipelineModel,
From 132875bb34868850428c1832a7bcd0b0315aeda2 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Thu, 23 Feb 2023 13:06:06 +0100
Subject: [PATCH 013/177] Remove unused import
---
nopaque.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/nopaque.py b/nopaque.py
index bbcf799d..b369556a 100644
--- a/nopaque.py
+++ b/nopaque.py
@@ -13,7 +13,6 @@ from app.models import (
Job,
JobInput,
JobResult,
- Permission,
Role,
TesseractOCRPipelineModel,
SpaCyNLPPipelineModel,
From 1d85e96d3afbcbcaa8c33667fd96011523ee0bf4 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Thu, 23 Feb 2023 15:18:53 +0100
Subject: [PATCH 014/177] Let the Corpus owner change Roles of followers
---
app/models.py | 39 ++++++++++++++-----
.../js/ResourceLists/CorpusFollowerList.js | 7 ++--
app/static/js/Utils.js | 27 ++-----------
3 files changed, 37 insertions(+), 36 deletions(-)
diff --git a/app/models.py b/app/models.py
index 2444589c..01e7c09a 100644
--- a/app/models.py
+++ b/app/models.py
@@ -37,6 +37,16 @@ class CorpusStatus(IntEnum):
RUNNING_ANALYSIS_SESSION = 8
CANCELING_ANALYSIS_SESSION = 9
+ @staticmethod
+ def get(corpus_status: Union['CorpusStatus', int, str]) -> 'CorpusStatus':
+ if isinstance(corpus_status, CorpusStatus):
+ return corpus_status
+ if isinstance(corpus_status, int):
+ return CorpusStatus(corpus_status)
+ if isinstance(corpus_status, str):
+ return CorpusStatus[corpus_status]
+ raise TypeError('corpus_status must be CorpusStatus, int, or str')
+
class JobStatus(IntEnum):
INITIALIZING = 1
@@ -48,6 +58,16 @@ class JobStatus(IntEnum):
COMPLETED = 7
FAILED = 8
+ @staticmethod
+ def get(job_status: Union['JobStatus', int, str]) -> 'JobStatus':
+ if isinstance(job_status, JobStatus):
+ return job_status
+ if isinstance(job_status, int):
+ return JobStatus(job_status)
+ if isinstance(job_status, str):
+ return JobStatus[job_status]
+ raise TypeError('job_status must be JobStatus, int, or str')
+
class Permission(IntEnum):
'''
@@ -68,6 +88,7 @@ class Permission(IntEnum):
return Permission[permission]
raise TypeError('permission must be Permission, int, or str')
+
class UserSettingJobStatusMailNotificationLevel(IntEnum):
NONE = 1
END = 2
@@ -90,14 +111,14 @@ class CorpusFollowerPermission(IntEnum):
UPDATE_FOLLOWER = 64
@staticmethod
- def get(permission: Union['CorpusFollowerPermission', int, str]) -> 'CorpusFollowerPermission':
- if isinstance(permission, CorpusFollowerPermission):
- return permission
- if isinstance(permission, int):
- return CorpusFollowerPermission(permission)
- if isinstance(permission, str):
- return CorpusFollowerPermission[permission]
- raise TypeError('permission must be CorpusFollowerPermission, int, or str')
+ def get(corpus_follower_permission: Union['CorpusFollowerPermission', int, str]) -> 'CorpusFollowerPermission':
+ if isinstance(corpus_follower_permission, CorpusFollowerPermission):
+ return corpus_follower_permission
+ if isinstance(corpus_follower_permission, int):
+ return CorpusFollowerPermission(corpus_follower_permission)
+ if isinstance(corpus_follower_permission, str):
+ return CorpusFollowerPermission[corpus_follower_permission]
+ raise TypeError('corpus_follower_permission must be CorpusFollowerPermission, int, or str')
# endregion enums
@@ -555,7 +576,7 @@ class User(HashidMixin, UserMixin, db.Model):
cascade='all, delete-orphan',
lazy='dynamic'
)
-
+
def __init__(self, **kwargs):
super().__init__(**kwargs)
if self.role is not None:
diff --git a/app/static/js/ResourceLists/CorpusFollowerList.js b/app/static/js/ResourceLists/CorpusFollowerList.js
index cc94c568..b0b621d2 100644
--- a/app/static/js/ResourceLists/CorpusFollowerList.js
+++ b/app/static/js/ResourceLists/CorpusFollowerList.js
@@ -41,9 +41,9 @@ class CorpusFollowerList extends ResourceList {
- Viewer
- Contributor
- Administrator
+ Viewer
+ Contributor
+ Administrator
@@ -176,6 +176,7 @@ class CorpusFollowerList extends ResourceList {
case 'replace': {
let re = new RegExp(`^/users/${this.userId}/corpora/${this.corpusId}/corpus_follower_associations/([A-Za-z0-9]*)/role$`);
if (re.test(operation.path)) {
+ console.log('role updated');
let [match, jobId, valueName] = operation.path.match(re);
this.replace(jobId, valueName, operation.value);
}
diff --git a/app/static/js/Utils.js b/app/static/js/Utils.js
index 354f0f63..f8dbf2d0 100644
--- a/app/static/js/Utils.js
+++ b/app/static/js/Utils.js
@@ -69,13 +69,13 @@ class Utils {
return Utils.mergeObjectsDeep(mergedObject, ...objects.slice(2));
}
- static addCorpusFollowerPermissionRequest(corpusId, followerId, permission) {
+ static updateCorpusFollowerRole(corpusId, followerId, roleName) {
return new Promise((resolve, reject) => {
- fetch(`/corpora/${corpusId}/followers/${followerId}/permissions/${permission}/add`, {method: 'POST', headers: {Accept: 'application/json'}})
+ fetch(`/corpora/${corpusId}/followers/${followerId}/role`, {method: 'POST', headers: {Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({role: roleName})})
.then(
(response) => {
if (response.ok) {
- app.flash(`Permission added`, 'corpus');
+ app.flash('Role updated', 'corpus');
resolve(response);
return;
} else {
@@ -91,27 +91,6 @@ class Utils {
});
}
- static removeCorpusFollowerPermissionRequest(corpusId, followerId, permission) {
- return new Promise((resolve, reject) => {
- fetch(`/corpora/${corpusId}/followers/${followerId}/permissions/${permission}/remove`, {method: 'POST', headers: {Accept: 'application/json'}})
- .then(
- (response) => {
- if (response.ok) {
- app.flash(`Permission removed`, 'corpus');
- resolve(response);
- } else {
- app.flash(`${response.statusText}`, 'error');
- reject(response);
- }
- },
- (response) => {
- app.flash('Something went wrong', 'error');
- reject(response);
- }
- );
- });
- }
-
static enableCorpusIsPublicRequest(userId, corpusId) {
return new Promise((resolve, reject) => {
let corpus;
From 0609e2cd7239c74e1ffb9a7c2c15294e6797cb65 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 09:27:20 +0100
Subject: [PATCH 015/177] Fix follow corpus mechanics
---
app/models.py | 21 +++++++++------------
1 file changed, 9 insertions(+), 12 deletions(-)
diff --git a/app/models.py b/app/models.py
index 01e7c09a..ed36a8ff 100644
--- a/app/models.py
+++ b/app/models.py
@@ -378,8 +378,7 @@ class CorpusFollowerRole(HashidMixin, db.Model):
# Relationships
corpus_follower_associations = db.relationship(
'CorpusFollowerAssociation',
- back_populates='role',
- lazy='dynamic'
+ back_populates='role'
)
def __repr__(self):
@@ -481,11 +480,9 @@ class CorpusFollowerAssociation(HashidMixin, db.Model):
def __init__(self, **kwargs):
super().__init__(**kwargs)
- if self.role is None:
- self.role = CorpusFollowerRole.query.filter_by(default=True).first()
def __repr__(self):
- return f''
+ return f''
def to_json_serializeable(self, backrefs=False, relationships=False):
json_serializeable = {
@@ -545,8 +542,7 @@ class User(HashidMixin, UserMixin, db.Model):
)
followed_corpora = association_proxy(
'corpus_follower_associations',
- 'corpus',
- creator=lambda c: CorpusFollowerAssociation(corpus=c)
+ 'corpus'
)
jobs = db.relationship(
'Job',
@@ -778,9 +774,11 @@ class User(HashidMixin, UserMixin, db.Model):
self.profile_privacy_settings = 0
#endregion Profile Privacy settings
- def follow_corpus(self, corpus):
- if not self.is_following_corpus(corpus):
- self.followed_corpora.append(corpus)
+ def follow_corpus(self, corpus, role=None):
+ if role is None:
+ r = CorpusFollowerRole.query.filter_by(default=True).first()
+ cfa = CorpusFollowerAssociation(corpus=corpus, role=r, follower=self)
+ db.session.add(cfa)
def unfollow_corpus(self, corpus):
if self.is_following_corpus(corpus):
@@ -1499,8 +1497,7 @@ class Corpus(HashidMixin, db.Model):
)
followers = association_proxy(
'corpus_follower_associations',
- 'follower',
- creator=lambda u: CorpusFollowerAssociation(followers=u)
+ 'follower'
)
user = db.relationship('User', back_populates='corpora')
# "static" attributes
From b27a1051af79e0362ab20c6663e7e9950c20273b Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Fri, 24 Feb 2023 09:30:29 +0100
Subject: [PATCH 016/177] import share link token generation to models.py
---
app/corpora/routes.py | 32 ++++----------------------------
app/models.py | 33 ++++++++++++++++++++++++++++++++-
2 files changed, 36 insertions(+), 29 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index 1c669f61..fd718145 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -69,19 +69,9 @@ def disable_corpus_is_public(corpus_id):
@login_required
def follow_corpus(corpus_id, token):
corpus = Corpus.query.get_or_404(corpus_id)
- try:
- payload = jwt.decode(
- token,
- current_app.config['SECRET_KEY'],
- algorithms=['HS256'],
- issuer=current_app.config['SERVER_NAME'],
- # options={'require': ['exp', 'iat', 'iss', 'sub']}
- options={'require': ['exp', 'iat', 'iss']}
- )
- except jwt.PyJWTError:
- abort(410)
- # permission = payload.get('sub')
- if not current_user.is_following_corpus(corpus):
+ if not (current_user.is_authenticated and current_user.verify_follow_corpus_token(token)):
+ abort(403)
+ if not current_user.is_following_corpus(corpus) and current_user != corpus.user:
current_user.follow_corpus(corpus)
db.session.commit()
flash(f'You are following {corpus.title} now', category='corpus')
@@ -174,9 +164,6 @@ def create_corpus():
def corpus(corpus_id):
corpus = Corpus.query.get_or_404(corpus_id)
exp_date = (datetime.utcnow() + timedelta(days=7)).strftime('%b %d, %Y')
- print(corpus.user)
- print(current_user)
- print(current_user.is_following_corpus(corpus))
if corpus.user == current_user or current_user.is_administrator():
return render_template(
'corpora/corpus.html.j2',
@@ -201,18 +188,7 @@ def generate_corpus_share_link(corpus_id):
# permission = data['permission']
exp_data = data['expiration']
expiration = datetime.strptime(exp_data, '%b %d, %Y')
- now = datetime.utcnow()
- payload = {
- 'exp': expiration,
- 'iat': now,
- 'iss': current_app.config['SERVER_NAME']
- # 'sub': permission
- }
- token = jwt.encode(
- payload,
- current_app.config['SECRET_KEY'],
- algorithm='HS256'
- )
+ token = current_user.generate_follow_corpus_token(corpus_id, expiration)
link = url_for('corpora.follow_corpus', corpus_id=corpus_id, token=token, _external=True)
return link
diff --git a/app/models.py b/app/models.py
index 2444589c..7dc6b0c3 100644
--- a/app/models.py
+++ b/app/models.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
from enum import Enum, IntEnum
-from flask import current_app, url_for
+from flask import abort, current_app, url_for
from flask_hashids import HashidMixin
from flask_login import UserMixin
from sqlalchemy.ext.associationproxy import association_proxy
@@ -767,6 +767,37 @@ class User(HashidMixin, UserMixin, db.Model):
def is_following_corpus(self, corpus):
return corpus in self.followed_corpora
+
+ def generate_follow_corpus_token(self, corpus_id, expiration=7):
+ now = datetime.utcnow()
+ payload = {
+ 'exp': expiration,
+ 'iat': now,
+ 'iss': current_app.config['SERVER_NAME'],
+ 'sub': corpus_id
+ }
+ return jwt.encode(
+ payload,
+ current_app.config['SECRET_KEY'],
+ algorithm='HS256'
+ )
+
+ def verify_follow_corpus_token(self, token):
+ try:
+ payload = jwt.decode(
+ token,
+ current_app.config['SECRET_KEY'],
+ algorithms=['HS256'],
+ issuer=current_app.config['SERVER_NAME'],
+ options={'require': ['exp', 'iat', 'iss', 'sub']}
+ )
+ except jwt.PyJWTError:
+ return False
+ corpus_id = payload.get('sub')
+ corpus = Corpus.query.get_or_404(corpus_id)
+ if corpus is None:
+ return False
+ return True
def to_json_serializeable(self, backrefs=False, relationships=False, filter_by_privacy_settings=False):
json_serializeable = {
From cb31afe7236fdf37a43db8b14fa3ecbebac91fac Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 09:44:09 +0100
Subject: [PATCH 017/177] small fix
---
app/models.py | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/app/models.py b/app/models.py
index ed36a8ff..4f31c570 100644
--- a/app/models.py
+++ b/app/models.py
@@ -775,14 +775,17 @@ class User(HashidMixin, UserMixin, db.Model):
#endregion Profile Privacy settings
def follow_corpus(self, corpus, role=None):
+ if self.is_following_corpus(corpus):
+ return
if role is None:
r = CorpusFollowerRole.query.filter_by(default=True).first()
cfa = CorpusFollowerAssociation(corpus=corpus, role=r, follower=self)
db.session.add(cfa)
def unfollow_corpus(self, corpus):
- if self.is_following_corpus(corpus):
- self.followed_corpora.remove(corpus)
+ if not self.is_following_corpus(corpus):
+ return
+ self.followed_corpora.remove(corpus)
def is_following_corpus(self, corpus):
return corpus in self.followed_corpora
From 122cce98a160bf4432fa012eada338a61c58f769 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 09:46:35 +0100
Subject: [PATCH 018/177] another small fix
---
app/models.py | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/app/models.py b/app/models.py
index 4f31c570..c71445f9 100644
--- a/app/models.py
+++ b/app/models.py
@@ -777,8 +777,7 @@ class User(HashidMixin, UserMixin, db.Model):
def follow_corpus(self, corpus, role=None):
if self.is_following_corpus(corpus):
return
- if role is None:
- r = CorpusFollowerRole.query.filter_by(default=True).first()
+ r = CorpusFollowerRole.query.filter_by(default=True).first() if role is None else role
cfa = CorpusFollowerAssociation(corpus=corpus, role=r, follower=self)
db.session.add(cfa)
From ff3ac3658fd22c3b27da0c9c8843944f14728d5e Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 10:02:28 +0100
Subject: [PATCH 019/177] Yet another small fix
---
app/models.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/app/models.py b/app/models.py
index c71445f9..d73b01b6 100644
--- a/app/models.py
+++ b/app/models.py
@@ -542,7 +542,8 @@ class User(HashidMixin, UserMixin, db.Model):
)
followed_corpora = association_proxy(
'corpus_follower_associations',
- 'corpus'
+ 'corpus',
+ creator=lambda c: CorpusFollowerAssociation(corpus=c)
)
jobs = db.relationship(
'Job',
@@ -1499,7 +1500,8 @@ class Corpus(HashidMixin, db.Model):
)
followers = association_proxy(
'corpus_follower_associations',
- 'follower'
+ 'follower',
+ creator=lambda u: CorpusFollowerAssociation(follower=u)
)
user = db.relationship('User', back_populates='corpora')
# "static" attributes
From c565b08f9c9aecfc384fce1a0a58189890aafb66 Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 10:30:42 +0100
Subject: [PATCH 020/177] Found a better solution for default role assignments
---
app/models.py | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/app/models.py b/app/models.py
index d73b01b6..df992ccb 100644
--- a/app/models.py
+++ b/app/models.py
@@ -479,6 +479,8 @@ class CorpusFollowerAssociation(HashidMixin, db.Model):
)
def __init__(self, **kwargs):
+ if 'role' not in kwargs:
+ kwargs['role'] = CorpusFollowerRole.query.filter_by(default=True).first()
super().__init__(**kwargs)
def __repr__(self):
@@ -575,13 +577,12 @@ class User(HashidMixin, UserMixin, db.Model):
)
def __init__(self, **kwargs):
+ if 'role' not in kwargs:
+ if kwargs['email'] == current_app.config['NOPAQUE_ADMIN']:
+ kwargs['role'] = Role.query.filter_by(name='Administrator').first()
+ else:
+ kwargs['role'] = Role.query.filter_by(default=True).first()
super().__init__(**kwargs)
- if self.role is not None:
- return
- if self.email == current_app.config['NOPAQUE_ADMIN']:
- self.role = Role.query.filter_by(name='Administrator').first()
- else:
- self.role = Role.query.filter_by(default=True).first()
def __repr__(self):
return f''
From 3147bed90acdd9a7321479274352a3b6d589760d Mon Sep 17 00:00:00 2001
From: Patrick Jentsch
Date: Fri, 24 Feb 2023 10:34:42 +0100
Subject: [PATCH 021/177] codestyle enhancements
---
app/models.py | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/app/models.py b/app/models.py
index df992ccb..2800e767 100644
--- a/app/models.py
+++ b/app/models.py
@@ -578,10 +578,11 @@ class User(HashidMixin, UserMixin, db.Model):
def __init__(self, **kwargs):
if 'role' not in kwargs:
- if kwargs['email'] == current_app.config['NOPAQUE_ADMIN']:
- kwargs['role'] = Role.query.filter_by(name='Administrator').first()
- else:
- kwargs['role'] = Role.query.filter_by(default=True).first()
+ kwargs['role'] = (
+ Role.query.filter_by(name='Administrator').first()
+ if kwargs['email'] == current_app.config['NOPAQUE_ADMIN']
+ else Role.query.filter_by(default=True).first()
+ )
super().__init__(**kwargs)
def __repr__(self):
From e2ddbf26f1faf6d9b3adcdfa48bd8279514160fa Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Fri, 24 Feb 2023 15:22:26 +0100
Subject: [PATCH 022/177] Update User Card and Share link with specific role
---
app/corpora/routes.py | 15 ++++--
app/models.py | 8 ++--
.../js/RessourceDisplays/CorpusDisplay.js | 5 +-
app/static/js/Utils.js | 6 +--
app/templates/corpora/corpus.html.j2 | 14 +++---
app/templates/corpora/public_corpus.html.j2 | 46 +++++++++++++++++--
6 files changed, 69 insertions(+), 25 deletions(-)
diff --git a/app/corpora/routes.py b/app/corpora/routes.py
index fd718145..ecb74cae 100644
--- a/app/corpora/routes.py
+++ b/app/corpora/routes.py
@@ -68,11 +68,12 @@ def disable_corpus_is_public(corpus_id):
@bp.route('//follow/')
@login_required
def follow_corpus(corpus_id, token):
- corpus = Corpus.query.get_or_404(corpus_id)
+ corpus = current_user.verify_follow_corpus_token(token)['corpus']
+ role = current_user.verify_follow_corpus_token(token)['role']
if not (current_user.is_authenticated and current_user.verify_follow_corpus_token(token)):
abort(403)
if not current_user.is_following_corpus(corpus) and current_user != corpus.user:
- current_user.follow_corpus(corpus)
+ current_user.follow_corpus(corpus, role)
db.session.commit()
flash(f'You are following {corpus.title} now', category='corpus')
return redirect(url_for('corpora.corpus', corpus_id=corpus_id))
@@ -164,20 +165,24 @@ def create_corpus():
def corpus(corpus_id):
corpus = Corpus.query.get_or_404(corpus_id)
exp_date = (datetime.utcnow() + timedelta(days=7)).strftime('%b %d, %Y')
+ roles = [x.name for x in CorpusFollowerRole.query.all()]
if corpus.user == current_user or current_user.is_administrator():
return render_template(
'corpora/corpus.html.j2',
corpus=corpus,
exp_date=exp_date,
+ roles=roles,
title='Corpus'
)
if current_user.is_following_corpus(corpus) or corpus.is_public:
corpus_files = [x.to_json_serializeable() for x in corpus.files]
+ owner = corpus.user.to_json_serializeable()
return render_template(
'corpora/public_corpus.html.j2',
corpus=corpus,
corpus_files=corpus_files,
- title='Corpus'
+ owner=owner,
+ title='Corpus',
)
abort(403)
@@ -185,10 +190,10 @@ def corpus(corpus_id):
@login_required
def generate_corpus_share_link(corpus_id):
data = request.get_json('data')
- # permission = data['permission']
+ role = data['role']
exp_data = data['expiration']
expiration = datetime.strptime(exp_data, '%b %d, %Y')
- token = current_user.generate_follow_corpus_token(corpus_id, expiration)
+ token = current_user.generate_follow_corpus_token(corpus_id, role, expiration)
link = url_for('corpora.follow_corpus', corpus_id=corpus_id, token=token, _external=True)
return link
diff --git a/app/models.py b/app/models.py
index 74d82410..8fc08c18 100644
--- a/app/models.py
+++ b/app/models.py
@@ -789,13 +789,14 @@ class User(HashidMixin, UserMixin, db.Model):
def is_following_corpus(self, corpus):
return corpus in self.followed_corpora
- def generate_follow_corpus_token(self, corpus_id, expiration=7):
+ def generate_follow_corpus_token(self, corpus_id, role, expiration=7):
now = datetime.utcnow()
payload = {
'exp': expiration,
'iat': now,
'iss': current_app.config['SERVER_NAME'],
- 'sub': corpus_id
+ 'sub': corpus_id,
+ 'role': role
}
return jwt.encode(
payload,
@@ -816,9 +817,10 @@ class User(HashidMixin, UserMixin, db.Model):
return False
corpus_id = payload.get('sub')
corpus = Corpus.query.get_or_404(corpus_id)
+ role = CorpusFollowerRole.query.filter_by(name=payload.get('role')).first()
if corpus is None:
return False
- return True
+ return {'corpus': corpus, 'role': role}
def to_json_serializeable(self, backrefs=False, relationships=False, filter_by_privacy_settings=False):
json_serializeable = {
diff --git a/app/static/js/RessourceDisplays/CorpusDisplay.js b/app/static/js/RessourceDisplays/CorpusDisplay.js
index d42fa20c..4e8e8a9a 100644
--- a/app/static/js/RessourceDisplays/CorpusDisplay.js
+++ b/app/static/js/RessourceDisplays/CorpusDisplay.js
@@ -124,13 +124,12 @@ class CorpusDisplay extends RessourceDisplay {
let copyShareLinkButton = this.displayElement.querySelector('#copy-share-link-button');
let shareLinkInput = this.displayElement.querySelector('#share-link-input');
let shareLinkContainer = this.displayElement.querySelector('#share-link-container');
- // let permissionSelect = this.displayElement.querySelector('#permission-select');
+ let roleSelect = this.displayElement.querySelector('#role-select');
let expirationDate = this.displayElement.querySelector('#expiration');
generateShareLinkButton.addEventListener('click', () => {
- // Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, permissionSelect.value, expirationDate.value)
- Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, expirationDate.value)
+ Utils.generateCorpusShareLinkRequest(`${this.corpusId}`, roleSelect.value, expirationDate.value)
.then((shareLink) => {
shareLinkContainer.classList.remove('hide');
shareLinkInput.value = shareLink;
diff --git a/app/static/js/Utils.js b/app/static/js/Utils.js
index f8dbf2d0..865ea0d4 100644
--- a/app/static/js/Utils.js
+++ b/app/static/js/Utils.js
@@ -757,11 +757,9 @@ class Utils {
});
}
- // static generateCorpusShareLinkRequest(corpusId, permission, expiration) {
- static generateCorpusShareLinkRequest(corpusId, expiration) {
+ static generateCorpusShareLinkRequest(corpusId, role, expiration) {
return new Promise((resolve, reject) => {
- // const data = {permission: permission, expiration: expiration};
- const data = {expiration: expiration};
+ const data = {role: role, expiration: expiration};
fetch(`/corpora/${corpusId}/generate-corpus-share-link`, {method: 'POST', headers: {Accept: 'text/plain'}, body: JSON.stringify(data)})
.then(
(response) => {
diff --git a/app/templates/corpora/corpus.html.j2 b/app/templates/corpora/corpus.html.j2
index 196faef2..84950403 100644
--- a/app/templates/corpora/corpus.html.j2
+++ b/app/templates/corpora/corpus.html.j2
@@ -96,18 +96,18 @@
- {#
+
-
- View
- Contribute
- Administrate
+
+ {% for role in roles%}
+ {{role}}
+ {% endfor %}
- Permission
+ Role
-
#}
+
From d2828cabbe6d1f7a14bf859d474a5106e90e41a7 Mon Sep 17 00:00:00 2001
From: Inga Kirschnick
Date: Fri, 24 Feb 2023 15:46:44 +0100
Subject: [PATCH 023/177] Explanation update and profile link button
---
app/templates/corpora/corpus.html.j2 | 11 +++++++++++
app/templates/corpora/public_corpus.html.j2 | 3 ++-
2 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/app/templates/corpora/corpus.html.j2 b/app/templates/corpora/corpus.html.j2
index 84950403..790d4fac 100644
--- a/app/templates/corpora/corpus.html.j2
+++ b/app/templates/corpora/corpus.html.j2
@@ -86,6 +86,9 @@
Share your Corpus
+ Change your Corpus Status to Public
+ Other users can only see the meta data of your corpus. The files of the corpus remain private and can only be viewed via a share link.
+
@@ -96,6 +99,14 @@
+
+
+
+ Create a link to share your corpus files with your team
+ With the link other users follow your corpus directly, if it has not expired.
+ You can set different roles via the link, you can also edit them later in the menu below.
+ It is recommended not to set the expiration date of the link too far.
+
diff --git a/app/templates/corpora/public_corpus.html.j2 b/app/templates/corpora/public_corpus.html.j2
index 17a7ae07..edf6ed74 100644
--- a/app/templates/corpora/public_corpus.html.j2
+++ b/app/templates/corpora/public_corpus.html.j2
@@ -68,11 +68,12 @@
- {% if not current_user.is_following_corpus(corpus) %}
+ {% if not current_user.is_following_corpus(corpus) %}
Request Corpus
{% endif %}
+ View profile
Social
-Find other users and follow them to see their corpora.
- -Find public corpora
- -