Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

154 linhas
5.6KB

  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. import json
  18. from sqlalchemy.sql import func
  19. import markdown
  20. # function to retrieve data about a single resource from the database
  21. def get_resource(resource_id):
  22. resource = Resource.query.filter_by(id=resource_id).first()
  23. if resource is None:
  24. abort(404)
  25. return resource
  26. # function to retrieve data about a resource and its relationships
  27. def get_full_resource(resource_id):
  28. resource = get_resource(resource_id)
  29. resource = append_relationships(resource)
  30. if resource.type == 'book':
  31. # render Markdown as HTML
  32. resource.description = markdown.markdown(resource.description)
  33. # get additional book metadata
  34. book_data = get_book_data(resource.isbn)
  35. if book_data:
  36. resource.__dict__.update(book_data)
  37. # if there's a GitHub repository link, get last GitHub commit date
  38. if resource.repositoryUrl and "github" in resource.repositoryUrl:
  39. # get commit date
  40. date = get_commit_date(resource.repositoryUrl)
  41. resource.__dict__['commitDate'] = date
  42. return resource
  43. # function to get practice from Markdown file
  44. def get_practice_markdown(practice_name, option='html'):
  45. file_name = practice_name.replace(" ", "_")
  46. with open(f'content/practices/{file_name}.md', 'r') as f:
  47. practice_text = f.read()
  48. if option == 'html':
  49. practice_text = markdown.markdown(practice_text)
  50. return practice_text
  51. # function to write new or edited practice to Markdown file
  52. def write_practice_markdown(practice_name, markdown):
  53. practice_name = practice_name.replace(" ", "_")
  54. with open(f'content/practices/{practice_name}.md', 'w+') as f:
  55. f.write(markdown)
  56. # function to extract only the first paragraph of practice Markdown
  57. def extract_first_paragraph(markdown):
  58. # Split the text into lines
  59. lines = markdown.split("\n")
  60. # Initialize a flag to track when we find the first paragraph
  61. paragraph = []
  62. for line in lines:
  63. # Ignore headings (lines starting with #)
  64. if line.startswith("#"):
  65. continue
  66. # If the line is not empty, it's part of a paragraph
  67. if line.strip():
  68. paragraph.append(line.strip())
  69. elif paragraph: # Stop once we have collected a paragraph and hit an empty line
  70. break
  71. return " ".join(paragraph)
  72. # function to retrieve data about a curated list of resources
  73. def get_curated_resources(resource_ids):
  74. resources = Resource.query.filter(Resource.id.in_(resource_ids)).filter_by(published=True).order_by(func.random()).all()
  75. # append relationships to each resource
  76. append_relationships_multiple(resources)
  77. return resources
  78. # function to delete a single resource
  79. def delete_resource(resource_id):
  80. deletion = Resource.query.get(resource_id)
  81. db.session.delete(deletion)
  82. db.session.commit()
  83. flash('Successfully deleted!')
  84. # function to get filters for a specific field
  85. def get_filter_values(field, type):
  86. # get field values for filter
  87. field_filter = Resource.query.filter_by(type=type).filter_by(published=True).with_entities(getattr(Resource, field))
  88. # turn SQLAlchemy object into list
  89. field_filter = [i for i, in field_filter]
  90. # split each element on '/' (useful for scriptingLanguage only)
  91. field_filter = [y for x in field_filter for y in x.split(' / ')]
  92. # consolidate duplicate values
  93. field_filter = list(dict.fromkeys(field_filter))
  94. # filter None values from list
  95. field_filter = filter(None, field_filter)
  96. # sort list by alphabetical order
  97. field_filter = sorted(field_filter)
  98. return field_filter
  99. # function to get book data including metadata and covers
  100. def get_book_data(isbn):
  101. try:
  102. book = meta(isbn)
  103. description = {'desc': desc(isbn)}
  104. book.update(description)
  105. #book = get_book_cover(book)
  106. return book
  107. except:
  108. pass
  109. # function to get book cover data
  110. def get_book_cover(book):
  111. # get highest-resolution book cover possible
  112. openl_url = 'https://covers.openlibrary.org/b/isbn/' + book['ISBN-13'] + '-L.jpg?default=false'
  113. request = requests.get(openl_url)
  114. if request.status_code != 200:
  115. book.update(cover(isbn))
  116. else:
  117. book_cover = {'thumbnail': openl_url}
  118. book.update(book_cover)
  119. return book
  120. # function to retrieve last updated date from the database
  121. def get_last_date():
  122. resource = Resource.query.order_by(Resource.created.desc()).filter_by(published=True).first()
  123. return resource.created.isoformat()
  124. # function to retrieve last commit date from a GitHub repository for a tool
  125. def get_commit_date(repositoryUrl):
  126. # change repository URL to API URL
  127. api_url = repositoryUrl.replace("https://github.com", "https://api.github.com/repos")
  128. # get default branch name
  129. r = requests.get(api_url)
  130. r = json.loads(r.content)
  131. branch = r['default_branch']
  132. # get date of last commit on default branch
  133. api_url = api_url + "/branches/" + branch
  134. r = requests.get(api_url)
  135. r = json.loads(r.content)
  136. date = r['commit']['commit']['author']['date'][0:10]
  137. return date