Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

112 lines
6.0KB

  1. # @name: resources.py
  2. # @creation_date: 2022-02-23
  3. # @license: The MIT License <https://opensource.org/licenses/MIT>
  4. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  5. # @purpose: functions for resources
  6. # @acknowledgements:
  7. # isbntools: https://isbntools.readthedocs.io/en/latest/info.html
  8. # regex for URLs: https://gist.github.com/gruber/249502
  9. from flask import Blueprint, render_template, request, flash, redirect, url_for
  10. from .models import Resource
  11. from werkzeug.exceptions import abort
  12. from . import db
  13. from .relationships import *
  14. from isbntools.app import *
  15. import requests
  16. import re
  17. # function to retrieve data about a single resource from the database
  18. def get_resource(resource_id):
  19. resource = Resource.query.filter_by(id=resource_id).first()
  20. if resource is None:
  21. abort(404)
  22. return resource
  23. # function to retrieve data about a resource and its relationships
  24. def get_full_resource(resource_id):
  25. resource = get_resource(resource_id)
  26. resource = append_relationships(resource)
  27. if resource.type == 'book':
  28. book_data = get_book_data(resource.isbn)
  29. if book_data:
  30. resource.__dict__.update(book_data)
  31. return resource
  32. # function to delete a single resource
  33. def delete_resource(resource_id):
  34. deletion = Resource.query.get(resource_id)
  35. db.session.delete(deletion)
  36. db.session.commit()
  37. flash('Successfully deleted!')
  38. # function to get filters for a specific field
  39. def get_filter_values(field, type):
  40. # get field values for filter
  41. field_filter = Resource.query.filter_by(type=type).with_entities(getattr(Resource, field))
  42. # turn SQLAlchemy object into list
  43. field_filter = [i for i, in field_filter]
  44. # split each element on '/' (useful for scriptingLanguage only)
  45. field_filter = [y for x in field_filter for y in x.split(' / ')]
  46. # consolidate duplicate values
  47. field_filter = list(dict.fromkeys(field_filter))
  48. # filter None values from list
  49. field_filter = filter(None, field_filter)
  50. # sort list by alphabetical order
  51. field_filter = sorted(field_filter)
  52. return field_filter
  53. # function to get book data including metadata and covers
  54. def get_book_data(isbn):
  55. try:
  56. book = meta(isbn)
  57. description = {'desc': desc(isbn)}
  58. book.update(description)
  59. # get highest-resolution book cover possible
  60. openl_url = 'https://covers.openlibrary.org/b/isbn/' + book['ISBN-13'] + '-L.jpg?default=false'
  61. request = requests.get(openl_url)
  62. if request.status_code != 200:
  63. book.update(cover(isbn))
  64. else:
  65. book_cover = {'thumbnail': openl_url}
  66. book.update(book_cover)
  67. return book
  68. except:
  69. pass
  70. # function to get full metadata for a book and combine into one object
  71. # TO BE DELETED
  72. def get_book(resource_id):
  73. book = get_resource(resource_id)
  74. book_data = get_book_data(book.isbn)
  75. book.__dict__.update(book_data)
  76. return book
  77. # function to replace embedded URL strings with href links
  78. def replace_urls(input):
  79. # Compile a regular expression to match URLs.
  80. # This regular expression is not exhaustive and may not match all possible URLs.
  81. # It is intended to be a starting point and can be refined and expanded as needed.
  82. url_regex = re.compile(r'((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))')
  83. # Find all URLs in the input string using the regular expression.
  84. # This will return a list of Match objects, each of which represents a single URL in the string.
  85. matches = url_regex.finditer(input)
  86. # Iterate over the list of matches and replace each URL with an HTML link.
  87. for match in matches:
  88. # Get the full URL from the Match object.
  89. url = match.group(0)
  90. # Create the HTML link by wrapping the URL in an <a> tag.
  91. # If the URL does not include a protocol (e.g. "http://" or "https://"),
  92. # then add "http://" as the default protocol.
  93. if not url.startswith('http'):
  94. link = f'<a href="http://{url}">{url}</a>'
  95. else:
  96. link = f'<a href="{url}">{url}</a>'
  97. # Replace the URL in the original string with the HTML link.
  98. input = input.replace(url, link)
  99. return input