A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

132 lines
4.8 KiB

  1. # -*- coding: utf-8 -*-
  2. from collections import OrderedDict
  3. from .highlighter import highlight_delta
  4. from .checker import do_check, T_POSSIBLE, T_SUSPECT
  5. from .misc import Query, cache
  6. from .sites import update_sites
  7. __all__ = ["format_api_error", "handle_api_request"]
  8. _CHECK_ERRORS = {
  9. "no search method": "Either 'use_engine' or 'use_links' must be true",
  10. "no URL": "The parameter 'url' is required for URL comparisons",
  11. "bad URI": "The given URI scheme is unsupported",
  12. "no data": "No text could be found in the given URL (note that only HTML "
  13. "and plain text pages are supported, and content generated by "
  14. "JavaScript or found inside iframes is ignored)",
  15. "timeout": "The given URL timed out before any data could be retrieved",
  16. "search error": "An error occurred while using the search engine; try "
  17. "reloading or setting 'use_engine' to 0",
  18. }
  19. def _serialize_page(page):
  20. return OrderedDict((("title", page.title), ("url", page.url)))
  21. def _serialize_source(source, show_skip=True):
  22. if not source:
  23. return OrderedDict((
  24. ("url", None), ("confidence", 0.0), ("violation", "none")))
  25. conf = source.confidence
  26. data = OrderedDict((
  27. ("url", source.url),
  28. ("confidence", conf),
  29. ("violation", "suspected" if conf >= T_SUSPECT else
  30. "possible" if conf >= T_POSSIBLE else "none")
  31. ))
  32. if show_skip:
  33. data["skipped"] = source.skipped
  34. data["excluded"] = source.excluded
  35. return data
  36. def _serialize_detail(result):
  37. article = highlight_delta(result.article_chain, result.best.chains[1])
  38. source = highlight_delta(result.best.chains[0], result.best.chains[1])
  39. return OrderedDict((("article", article), ("source", source)))
  40. def format_api_error(code, info):
  41. if isinstance(info, BaseException):
  42. info = type(info).__name__ + ": " + str(info)
  43. elif isinstance(info, unicode):
  44. info = info.encode("utf8")
  45. error_inner = OrderedDict((("code", code), ("info", info)))
  46. return OrderedDict((("status", "error"), ("error", error_inner)))
  47. def _hook_default(query):
  48. info = u"Unknown action: '{0}'".format(query.action.lower())
  49. return format_api_error("unknown_action", info)
  50. def _hook_check(query):
  51. do_check(query)
  52. if not query.submitted:
  53. info = ("The query parameters 'project', 'lang', and either 'title' "
  54. "or 'oldid' are required for checks")
  55. return format_api_error("missing_params", info)
  56. if query.error:
  57. info = _CHECK_ERRORS.get(query.error, "An unknown error occurred")
  58. return format_api_error(query.error.replace(" ", "_"), info)
  59. elif not query.site:
  60. info = (u"The given site (project={0}, lang={1}) either doesn't exist,"
  61. u" is closed, or is private").format(query.project, query.lang)
  62. return format_api_error("bad_site", info)
  63. elif not query.result:
  64. if query.oldid:
  65. info = u"The given revision ID doesn't seem to exist: {0}"
  66. return format_api_error("bad_oldid", info.format(query.oldid))
  67. else:
  68. info = u"The given page doesn't seem to exist: {0}"
  69. return format_api_error("bad_title", info.format(query.page.title))
  70. result = query.result
  71. data = OrderedDict((
  72. ("status", "ok"),
  73. ("meta", OrderedDict((
  74. ("time", result.time),
  75. ("queries", result.queries),
  76. ("cached", result.cached),
  77. ("redirected", bool(query.redirected_from))
  78. ))),
  79. ("page", _serialize_page(query.page))
  80. ))
  81. if result.cached:
  82. data["meta"]["cache_time"] = result.cache_time
  83. if query.redirected_from:
  84. data["original_page"] = _serialize_page(query.redirected_from)
  85. data["best"] = _serialize_source(result.best, show_skip=False)
  86. data["sources"] = [_serialize_source(source) for source in result.sources]
  87. if query.detail in ("1", "true"):
  88. data["detail"] = _serialize_detail(result)
  89. return data
  90. def _hook_sites(query):
  91. update_sites()
  92. return OrderedDict((
  93. ("status", "ok"), ("langs", cache.langs), ("projects", cache.projects)
  94. ))
  95. _HOOKS = {
  96. "compare": _hook_check,
  97. "search": _hook_check,
  98. "sites": _hook_sites,
  99. }
  100. def handle_api_request():
  101. query = Query()
  102. if query.version:
  103. try:
  104. query.version = int(query.version)
  105. except ValueError:
  106. info = "The version string is invalid: {0}".format(query.version)
  107. return format_api_error("invalid_version", info)
  108. else:
  109. query.version = 1
  110. if query.version == 1:
  111. action = query.action.lower() if query.action else ""
  112. return _HOOKS.get(action, _hook_default)(query)
  113. info = "The API version is unsupported: {0}".format(query.version)
  114. return format_api_error("unsupported_version", info)