views.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. # GNU MediaGoblin -- federated, autonomous media hosting
  2. # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. import json
  17. import io
  18. import mimetypes
  19. from werkzeug.datastructures import FileStorage
  20. from mediagoblin.decorators import oauth_required, require_active_login
  21. from mediagoblin.api.decorators import user_has_privilege
  22. from mediagoblin.db.models import User, LocalUser, MediaEntry, Comment, TextComment, Activity
  23. from mediagoblin.tools.federation import create_activity, create_generator
  24. from mediagoblin.tools.routing import extract_url_arguments
  25. from mediagoblin.tools.response import redirect, json_response, json_error, \
  26. render_404, render_to_response
  27. from mediagoblin.meddleware.csrf import csrf_exempt
  28. from mediagoblin.submit.lib import new_upload_entry, api_upload_request, \
  29. api_add_to_feed
  30. # MediaTypes
  31. from mediagoblin.media_types.image import MEDIA_TYPE as IMAGE_MEDIA_TYPE
  32. # Getters
  33. def get_profile(request):
  34. """
  35. Gets the user's profile for the endpoint requested.
  36. For example an endpoint which is /api/{username}/feed
  37. as /api/cwebber/feed would get cwebber's profile. This
  38. will return a tuple (username, user_profile). If no user
  39. can be found then this function returns a (None, None).
  40. """
  41. username = request.matchdict["username"]
  42. user = LocalUser.query.filter(LocalUser.username==username).first()
  43. if user is None:
  44. return None, None
  45. return user, user.serialize(request)
  46. # Endpoints
  47. @oauth_required
  48. def profile_endpoint(request):
  49. """ This is /api/user/<username>/profile - This will give profile info """
  50. user, user_profile = get_profile(request)
  51. if user is None:
  52. username = request.matchdict["username"]
  53. return json_error(
  54. "No such 'user' with username '{0}'".format(username),
  55. status=404
  56. )
  57. # user profiles are public so return information
  58. return json_response(user_profile)
  59. @oauth_required
  60. def user_endpoint(request):
  61. """ This is /api/user/<username> - This will get the user """
  62. user, user_profile = get_profile(request)
  63. if user is None:
  64. username = request.matchdict["username"]
  65. return json_error(
  66. "No such 'user' with username '{0}'".format(username),
  67. status=404
  68. )
  69. return json_response({
  70. "nickname": user.username,
  71. "updated": user.created.isoformat(),
  72. "published": user.created.isoformat(),
  73. "profile": user_profile,
  74. })
  75. @oauth_required
  76. @csrf_exempt
  77. @user_has_privilege(u'uploader')
  78. def uploads_endpoint(request):
  79. """ Endpoint for file uploads """
  80. username = request.matchdict["username"]
  81. requested_user = LocalUser.query.filter(LocalUser.username==username).first()
  82. if requested_user is None:
  83. return json_error("No such 'user' with id '{0}'".format(username), 404)
  84. if request.method == "POST":
  85. # Ensure that the user is only able to upload to their own
  86. # upload endpoint.
  87. if requested_user.id != request.user.id:
  88. return json_error(
  89. "Not able to post to another users feed.",
  90. status=403
  91. )
  92. # Wrap the data in the werkzeug file wrapper
  93. if "Content-Type" not in request.headers:
  94. return json_error(
  95. "Must supply 'Content-Type' header to upload media."
  96. )
  97. mimetype = request.headers["Content-Type"]
  98. filename = mimetypes.guess_all_extensions(mimetype)
  99. filename = 'unknown' + filename[0] if filename else filename
  100. file_data = FileStorage(
  101. stream=io.BytesIO(request.data),
  102. filename=filename,
  103. content_type=mimetype
  104. )
  105. # Find media manager
  106. entry = new_upload_entry(request.user)
  107. entry.media_type = IMAGE_MEDIA_TYPE
  108. return api_upload_request(request, file_data, entry)
  109. return json_error("Not yet implemented", 501)
  110. @oauth_required
  111. @csrf_exempt
  112. def inbox_endpoint(request, inbox=None):
  113. """ This is the user's inbox
  114. Currently because we don't have the ability to represent the inbox in the
  115. database this is not a "real" inbox in the pump.io/Activity streams 1.0
  116. sense but instead just gives back all the data on the website
  117. inbox: allows you to pass a query in to limit inbox scope
  118. """
  119. username = request.matchdict["username"]
  120. user = LocalUser.query.filter(LocalUser.username==username).first()
  121. if user is None:
  122. return json_error("No such 'user' with id '{0}'".format(username), 404)
  123. # Only the user who's authorized should be able to read their inbox
  124. if user.id != request.user.id:
  125. return json_error(
  126. "Only '{0}' can read this inbox.".format(user.username),
  127. 403
  128. )
  129. if inbox is None:
  130. inbox = Activity.query
  131. # Count how many items for the "totalItems" field
  132. total_items = inbox.count()
  133. # We want to make a query for all media on the site and then apply GET
  134. # limits where we can.
  135. inbox = inbox.order_by(Activity.published.desc())
  136. # Limit by the "count" (default: 20)
  137. try:
  138. limit = int(request.args.get("count", 20))
  139. except ValueError:
  140. limit = 20
  141. # Prevent the count being too big (pump uses 200 so we shall)
  142. limit = limit if limit <= 200 else 200
  143. # Apply the limit
  144. inbox = inbox.limit(limit)
  145. # Offset (default: no offset - first <count> results)
  146. inbox = inbox.offset(request.args.get("offset", 0))
  147. # build the inbox feed
  148. feed = {
  149. "displayName": "Activities for {0}".format(user.username),
  150. "author": user.serialize(request),
  151. "objectTypes": ["activity"],
  152. "url": request.base_url,
  153. "links": {"self": {"href": request.url}},
  154. "items": [],
  155. "totalItems": total_items,
  156. }
  157. for activity in inbox:
  158. try:
  159. feed["items"].append(activity.serialize(request))
  160. except AttributeError:
  161. # As with the feed endpint this occurs because of how we our
  162. # hard-deletion method. Some activites might exist where the
  163. # Activity object and/or target no longer exist, for this case we
  164. # should just skip them.
  165. pass
  166. return json_response(feed)
  167. @oauth_required
  168. @csrf_exempt
  169. def inbox_minor_endpoint(request):
  170. """ Inbox subset for less important Activities """
  171. inbox = Activity.query.filter(
  172. (Activity.verb == "update") | (Activity.verb == "delete")
  173. )
  174. return inbox_endpoint(request=request, inbox=inbox)
  175. @oauth_required
  176. @csrf_exempt
  177. def inbox_major_endpoint(request):
  178. """ Inbox subset for most important Activities """
  179. inbox = Activity.query.filter_by(verb="post")
  180. return inbox_endpoint(request=request, inbox=inbox)
  181. @oauth_required
  182. @csrf_exempt
  183. def feed_endpoint(request, outbox=None):
  184. """ Handles the user's outbox - /api/user/<username>/feed """
  185. username = request.matchdict["username"]
  186. requested_user = LocalUser.query.filter(LocalUser.username==username).first()
  187. # check if the user exists
  188. if requested_user is None:
  189. return json_error("No such 'user' with id '{0}'".format(username), 404)
  190. if request.data:
  191. data = json.loads(request.data.decode())
  192. else:
  193. data = {"verb": None, "object": {}}
  194. if request.method in ["POST", "PUT"]:
  195. # Validate that the activity is valid
  196. if "verb" not in data or "object" not in data:
  197. return json_error("Invalid activity provided.")
  198. # Check that the verb is valid
  199. if data["verb"] not in ["post", "update", "delete"]:
  200. return json_error("Verb not yet implemented", 501)
  201. # We need to check that the user they're posting to is
  202. # the person that they are.
  203. if requested_user.id != request.user.id:
  204. return json_error(
  205. "Not able to post to another users feed.",
  206. status=403
  207. )
  208. # Handle new posts
  209. if data["verb"] == "post":
  210. obj = data.get("object", None)
  211. if obj is None:
  212. return json_error("Could not find 'object' element.")
  213. if obj.get("objectType", None) == "comment":
  214. # post a comment
  215. if not request.user.has_privilege(u'commenter'):
  216. return json_error(
  217. "Privilege 'commenter' required to comment.",
  218. status=403
  219. )
  220. comment = TextComment(actor=request.user.id)
  221. comment.unserialize(data["object"], request)
  222. comment.save()
  223. # Create activity for comment
  224. generator = create_generator(request)
  225. activity = create_activity(
  226. verb="post",
  227. actor=request.user,
  228. obj=comment,
  229. target=comment.get_reply_to(),
  230. generator=generator
  231. )
  232. return json_response(activity.serialize(request))
  233. elif obj.get("objectType", None) == "image":
  234. # Posting an image to the feed
  235. media_id = extract_url_arguments(
  236. url=data["object"]["id"],
  237. urlmap=request.app.url_map
  238. )["id"]
  239. # Build public_id
  240. public_id = request.urlgen(
  241. "mediagoblin.api.object",
  242. object_type=obj["objectType"],
  243. id=media_id,
  244. qualified=True
  245. )
  246. media = MediaEntry.query.filter_by(
  247. public_id=public_id
  248. ).first()
  249. if media is None:
  250. return json_response(
  251. "No such 'image' with id '{0}'".format(media_id),
  252. status=404
  253. )
  254. if media.actor != request.user.id:
  255. return json_error(
  256. "Privilege 'commenter' required to comment.",
  257. status=403
  258. )
  259. if not media.unserialize(data["object"]):
  260. return json_error(
  261. "Invalid 'image' with id '{0}'".format(media_id)
  262. )
  263. # Add location if one exists
  264. if "location" in data:
  265. Location.create(data["location"], self)
  266. media.save()
  267. activity = api_add_to_feed(request, media)
  268. return json_response(activity.serialize(request))
  269. elif obj.get("objectType", None) is None:
  270. # They need to tell us what type of object they're giving us.
  271. return json_error("No objectType specified.")
  272. else:
  273. # Oh no! We don't know about this type of object (yet)
  274. object_type = obj.get("objectType", None)
  275. return json_error(
  276. "Unknown object type '{0}'.".format(object_type)
  277. )
  278. # Updating existing objects
  279. if data["verb"] == "update":
  280. # Check we've got a valid object
  281. obj = data.get("object", None)
  282. if obj is None:
  283. return json_error("Could not find 'object' element.")
  284. if "objectType" not in obj:
  285. return json_error("No objectType specified.")
  286. if "id" not in obj:
  287. return json_error("Object ID has not been specified.")
  288. obj_id = extract_url_arguments(
  289. url=obj["id"],
  290. urlmap=request.app.url_map
  291. )["id"]
  292. public_id = request.urlgen(
  293. "mediagoblin.api.object",
  294. object_type=obj["objectType"],
  295. id=obj_id,
  296. qualified=True
  297. )
  298. # Now try and find object
  299. if obj["objectType"] == "comment":
  300. if not request.user.has_privilege(u'commenter'):
  301. return json_error(
  302. "Privilege 'commenter' required to comment.",
  303. status=403
  304. )
  305. comment = TextComment.query.filter_by(
  306. public_id=public_id
  307. ).first()
  308. if comment is None:
  309. return json_error(
  310. "No such 'comment' with id '{0}'.".format(obj_id)
  311. )
  312. # Check that the person trying to update the comment is
  313. # the author of the comment.
  314. if comment.actor != request.user.id:
  315. return json_error(
  316. "Only author of comment is able to update comment.",
  317. status=403
  318. )
  319. if not comment.unserialize(data["object"], request):
  320. return json_error(
  321. "Invalid 'comment' with id '{0}'".format(obj["id"])
  322. )
  323. comment.save()
  324. # Create an update activity
  325. generator = create_generator(request)
  326. activity = create_activity(
  327. verb="update",
  328. actor=request.user,
  329. obj=comment,
  330. generator=generator
  331. )
  332. return json_response(activity.serialize(request))
  333. elif obj["objectType"] == "image":
  334. image = MediaEntry.query.filter_by(
  335. public_id=public_id
  336. ).first()
  337. if image is None:
  338. return json_error(
  339. "No such 'image' with the id '{0}'.".format(obj["id"])
  340. )
  341. # Check that the person trying to update the comment is
  342. # the author of the comment.
  343. if image.actor != request.user.id:
  344. return json_error(
  345. "Only uploader of image is able to update image.",
  346. status=403
  347. )
  348. if not image.unserialize(obj):
  349. return json_error(
  350. "Invalid 'image' with id '{0}'".format(obj_id)
  351. )
  352. image.generate_slug()
  353. image.save()
  354. # Create an update activity
  355. generator = create_generator(request)
  356. activity = create_activity(
  357. verb="update",
  358. actor=request.user,
  359. obj=image,
  360. generator=generator
  361. )
  362. return json_response(activity.serialize(request))
  363. elif obj["objectType"] == "person":
  364. # check this is the same user
  365. if "id" not in obj or obj["id"] != requested_user.id:
  366. return json_error(
  367. "Incorrect user id, unable to update"
  368. )
  369. requested_user.unserialize(obj)
  370. requested_user.save()
  371. generator = create_generator(request)
  372. activity = create_activity(
  373. verb="update",
  374. actor=request.user,
  375. obj=requested_user,
  376. generator=generator
  377. )
  378. return json_response(activity.serialize(request))
  379. elif data["verb"] == "delete":
  380. obj = data.get("object", None)
  381. if obj is None:
  382. return json_error("Could not find 'object' element.")
  383. if "objectType" not in obj:
  384. return json_error("No objectType specified.")
  385. if "id" not in obj:
  386. return json_error("Object ID has not been specified.")
  387. # Parse out the object ID
  388. obj_id = extract_url_arguments(
  389. url=obj["id"],
  390. urlmap=request.app.url_map
  391. )["id"]
  392. public_id = request.urlgen(
  393. "mediagoblin.api.object",
  394. object_type=obj["objectType"],
  395. id=obj_id,
  396. qualified=True
  397. )
  398. if obj.get("objectType", None) == "comment":
  399. # Find the comment asked for
  400. comment = TextComment.query.filter_by(
  401. public_id=public_id,
  402. actor=request.user.id
  403. ).first()
  404. if comment is None:
  405. return json_error(
  406. "No such 'comment' with id '{0}'.".format(obj_id)
  407. )
  408. # Make a delete activity
  409. generator = create_generator(request)
  410. activity = create_activity(
  411. verb="delete",
  412. actor=request.user,
  413. obj=comment,
  414. generator=generator
  415. )
  416. # Unfortunately this has to be done while hard deletion exists
  417. context = activity.serialize(request)
  418. # now we can delete the comment
  419. comment.delete()
  420. return json_response(context)
  421. if obj.get("objectType", None) == "image":
  422. # Find the image
  423. entry = MediaEntry.query.filter_by(
  424. public_id=public_id,
  425. actor=request.user.id
  426. ).first()
  427. if entry is None:
  428. return json_error(
  429. "No such 'image' with id '{0}'.".format(obj_id)
  430. )
  431. # Make the delete activity
  432. generator = create_generator(request)
  433. activity = create_activity(
  434. verb="delete",
  435. actor=request.user,
  436. obj=entry,
  437. generator=generator
  438. )
  439. # This is because we have hard deletion
  440. context = activity.serialize(request)
  441. # Now we can delete the image
  442. entry.delete()
  443. return json_response(context)
  444. elif request.method != "GET":
  445. return json_error(
  446. "Unsupported HTTP method {0}".format(request.method),
  447. status=501
  448. )
  449. feed = {
  450. "displayName": "Activities by {user}@{host}".format(
  451. user=request.user.username,
  452. host=request.host
  453. ),
  454. "objectTypes": ["activity"],
  455. "url": request.base_url,
  456. "links": {"self": {"href": request.url}},
  457. "author": request.user.serialize(request),
  458. "items": [],
  459. }
  460. # Create outbox
  461. if outbox is None:
  462. outbox = Activity.query.filter_by(actor=requested_user.id)
  463. else:
  464. outbox = outbox.filter_by(actor=requested_user.id)
  465. # We want the newest things at the top (issue: #1055)
  466. outbox = outbox.order_by(Activity.published.desc())
  467. # Limit by the "count" (default: 20)
  468. limit = request.args.get("count", 20)
  469. try:
  470. limit = int(limit)
  471. except ValueError:
  472. limit = 20
  473. # The upper most limit should be 200
  474. limit = limit if limit < 200 else 200
  475. # apply the limit
  476. outbox = outbox.limit(limit)
  477. # Offset (default: no offset - first <count> result)
  478. offset = request.args.get("offset", 0)
  479. try:
  480. offset = int(offset)
  481. except ValueError:
  482. offset = 0
  483. outbox = outbox.offset(offset)
  484. # Build feed.
  485. for activity in outbox:
  486. try:
  487. feed["items"].append(activity.serialize(request))
  488. except AttributeError:
  489. # This occurs because of how we hard-deletion and the object
  490. # no longer existing anymore. We want to keep the Activity
  491. # in case someone wishes to look it up but we shouldn't display
  492. # it in the feed.
  493. pass
  494. feed["totalItems"] = len(feed["items"])
  495. return json_response(feed)
  496. @oauth_required
  497. def feed_minor_endpoint(request):
  498. """ Outbox for minor activities such as updates """
  499. # If it's anything but GET pass it along
  500. if request.method != "GET":
  501. return feed_endpoint(request)
  502. outbox = Activity.query.filter(
  503. (Activity.verb == "update") | (Activity.verb == "delete")
  504. )
  505. return feed_endpoint(request, outbox=outbox)
  506. @oauth_required
  507. def feed_major_endpoint(request):
  508. """ Outbox for all major activities """
  509. # If it's anything but a GET pass it along
  510. if request.method != "GET":
  511. return feed_endpoint(request)
  512. outbox = Activity.query.filter_by(verb="post")
  513. return feed_endpoint(request, outbox=outbox)
  514. @oauth_required
  515. def object_endpoint(request):
  516. """ Lookup for a object type """
  517. object_type = request.matchdict["object_type"]
  518. try:
  519. object_id = request.matchdict["id"]
  520. except ValueError:
  521. error = "Invalid object ID '{0}' for '{1}'".format(
  522. request.matchdict["id"],
  523. object_type
  524. )
  525. return json_error(error)
  526. if object_type not in ["image"]:
  527. # not sure why this is 404, maybe ask evan. Maybe 400?
  528. return json_error(
  529. "Unknown type: {0}".format(object_type),
  530. status=404
  531. )
  532. public_id = request.urlgen(
  533. "mediagoblin.api.object",
  534. object_type=object_type,
  535. id=object_id,
  536. qualified=True
  537. )
  538. media = MediaEntry.query.filter_by(public_id=public_id).first()
  539. if media is None:
  540. return json_error(
  541. "Can't find '{0}' with ID '{1}'".format(object_type, object_id),
  542. status=404
  543. )
  544. return json_response(media.serialize(request))
  545. @oauth_required
  546. def object_comments(request):
  547. """ Looks up for the comments on a object """
  548. public_id = request.urlgen(
  549. "mediagoblin.api.object",
  550. object_type=request.matchdict["object_type"],
  551. id=request.matchdict["id"],
  552. qualified=True
  553. )
  554. media = MediaEntry.query.filter_by(public_id=public_id).first()
  555. if media is None:
  556. return json_error("Can't find '{0}' with ID '{1}'".format(
  557. request.matchdict["object_type"],
  558. request.matchdict["id"]
  559. ), 404)
  560. comments = media.serialize(request)
  561. comments = comments.get("replies", {
  562. "totalItems": 0,
  563. "items": [],
  564. "url": request.urlgen(
  565. "mediagoblin.api.object.comments",
  566. object_type=media.object_type,
  567. id=media.id,
  568. qualified=True
  569. )
  570. })
  571. comments["displayName"] = "Replies to {0}".format(comments["url"])
  572. comments["links"] = {
  573. "first": comments["url"],
  574. "self": comments["url"],
  575. }
  576. return json_response(comments)
  577. ##
  578. # RFC6415 - Web Host Metadata
  579. ##
  580. def host_meta(request):
  581. """
  582. This provides the host-meta URL information that is outlined
  583. in RFC6415. By default this should provide XRD+XML however
  584. if the client accepts JSON we will provide that over XRD+XML.
  585. The 'Accept' header is used to decude this.
  586. A client should use this endpoint to determine what URLs to
  587. use for OAuth endpoints.
  588. """
  589. links = [
  590. {
  591. "rel": "lrdd",
  592. "type": "application/json",
  593. "href": request.urlgen(
  594. "mediagoblin.webfinger.well-known.webfinger",
  595. qualified=True
  596. )
  597. },
  598. {
  599. "rel": "registration_endpoint",
  600. "href": request.urlgen(
  601. "mediagoblin.oauth.client_register",
  602. qualified=True
  603. ),
  604. },
  605. {
  606. "rel": "http://apinamespace.org/oauth/request_token",
  607. "href": request.urlgen(
  608. "mediagoblin.oauth.request_token",
  609. qualified=True
  610. ),
  611. },
  612. {
  613. "rel": "http://apinamespace.org/oauth/authorize",
  614. "href": request.urlgen(
  615. "mediagoblin.oauth.authorize",
  616. qualified=True
  617. ),
  618. },
  619. {
  620. "rel": "http://apinamespace.org/oauth/access_token",
  621. "href": request.urlgen(
  622. "mediagoblin.oauth.access_token",
  623. qualified=True
  624. ),
  625. },
  626. {
  627. "rel": "http://apinamespace.org/activitypub/whoami",
  628. "href": request.urlgen(
  629. "mediagoblin.webfinger.whoami",
  630. qualified=True
  631. ),
  632. },
  633. ]
  634. if "application/json" in request.accept_mimetypes:
  635. return json_response({"links": links})
  636. # provide XML+XRD
  637. return render_to_response(
  638. request,
  639. "mediagoblin/api/host-meta.xml",
  640. {"links": links},
  641. mimetype="application/xrd+xml"
  642. )
  643. def lrdd_lookup(request):
  644. """
  645. This is the lrdd endpoint which can lookup a user (or
  646. other things such as activities). This is as specified by
  647. RFC6415.
  648. The cleint must provide a 'resource' as a GET parameter which
  649. should be the query to be looked up.
  650. """
  651. if "resource" not in request.args:
  652. return json_error("No resource parameter", status=400)
  653. resource = request.args["resource"]
  654. if "@" in resource:
  655. # Lets pull out the username
  656. resource = resource[5:] if resource.startswith("acct:") else resource
  657. username, host = resource.split("@", 1)
  658. # Now lookup the user
  659. user = LocalUser.query.filter(LocalUser.username==username).first()
  660. if user is None:
  661. return json_error(
  662. "Can't find 'user' with username '{0}'".format(username))
  663. return json_response([
  664. {
  665. "rel": "http://webfinger.net/rel/profile-page",
  666. "href": user.url_for_self(request.urlgen),
  667. "type": "text/html"
  668. },
  669. {
  670. "rel": "self",
  671. "href": request.urlgen(
  672. "mediagoblin.api.user",
  673. username=user.username,
  674. qualified=True
  675. )
  676. },
  677. {
  678. "rel": "activity-outbox",
  679. "href": request.urlgen(
  680. "mediagoblin.api.feed",
  681. username=user.username,
  682. qualified=True
  683. )
  684. }
  685. ])
  686. else:
  687. return json_error("Unrecognized resource parameter", status=404)
  688. def whoami(request):
  689. """ /api/whoami - HTTP redirect to API profile """
  690. if request.user is None:
  691. return json_error("Not logged in.", status=401)
  692. profile = request.urlgen(
  693. "mediagoblin.api.user.profile",
  694. username=request.user.username,
  695. qualified=True
  696. )
  697. return redirect(request, location=profile)