ApiController.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Controller;
  12. use Composer\IO\NullIO;
  13. use Composer\Factory;
  14. use Composer\Repository\VcsRepository;
  15. use Packagist\WebBundle\Package\Updater;
  16. use Packagist\WebBundle\Entity\Package;
  17. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  23. /**
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. */
  26. class ApiController extends Controller
  27. {
  28. /**
  29. * @Template()
  30. * @Route("/packages.json", name="packages", defaults={"_format" = "json"})
  31. */
  32. public function packagesAction(Request $req)
  33. {
  34. if (!$req->query->all()) {
  35. return new Response(file_get_contents($this->container->getParameter('kernel.root_dir').'/../web/packages_root.json'));
  36. }
  37. $em = $this->get('doctrine')->getEntityManager();
  38. $filters = array(
  39. 'type' => $req->query->get('type'),
  40. 'tag' => $req->query->get('tag'),
  41. );
  42. gc_enable();
  43. $packages = $em->getRepository('Packagist\WebBundle\Entity\Package')
  44. ->getFullPackages(null, $filters);
  45. $notifyUrl = $this->generateUrl('track_download', array('name' => 'VND/PKG'));
  46. $data = array(
  47. 'notify' => str_replace('VND/PKG', '%package%', $notifyUrl),
  48. 'packages' => array(),
  49. );
  50. foreach ($packages as $package) {
  51. $versions = array();
  52. foreach ($package->getVersions() as $version) {
  53. $versions[$version->getVersion()] = $version->toArray();
  54. $em->detach($version);
  55. }
  56. $data['packages'][$package->getName()] = $versions;
  57. $em->detach($package);
  58. }
  59. unset($versions, $package, $packages);
  60. $response = new Response(json_encode($data), 200);
  61. $response->setSharedMaxAge(120);
  62. return $response;
  63. }
  64. /**
  65. * @Route("/api/github", name="github_postreceive", defaults={"_format" = "json"})
  66. * @Method({"POST"})
  67. */
  68. public function githubPostReceive(Request $request)
  69. {
  70. $payload = json_decode($request->request->get('payload'), true);
  71. if (!$payload || !isset($payload['repository']['url'])) {
  72. return new Response(json_encode(array('status' => 'error', 'message' => 'Missing or invalid payload',)), 406);
  73. }
  74. $username = $request->request->has('username') ?
  75. $request->request->get('username') :
  76. $request->query->get('username');
  77. $apiToken = $request->request->has('apiToken') ?
  78. $request->request->get('apiToken') :
  79. $request->query->get('apiToken');
  80. $doctrine = $this->get('doctrine');
  81. $user = $doctrine
  82. ->getRepository('PackagistWebBundle:User')
  83. ->findOneBy(array('username' => $username, 'apiToken' => $apiToken));
  84. if (!$user) {
  85. return new Response(json_encode(array('status' => 'error', 'message' => 'Invalid credentials',)), 403);
  86. }
  87. if (!preg_match('{(github.com/[\w.-]+/[\w.-]+?)(\.git)?$}', $payload['repository']['url'], $match)) {
  88. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not parse payload repository URL',)), 406);
  89. }
  90. $payloadRepositoryChunk = $match[1];
  91. foreach ($user->getPackages() as $package) {
  92. if (false !== strpos($package->getRepository(), $payloadRepositoryChunk)) {
  93. // We found the package that was referenced.
  94. $updater = new Updater($doctrine);
  95. $config = Factory::createConfig();
  96. $repository = new VcsRepository(array('url' => $package->getRepository()), new NullIO, $config);
  97. $package->setAutoUpdated(true);
  98. $doctrine->getEntityManager()->flush();
  99. $updater->update($package, $repository);
  100. return new Response('{"status": "success"}', 202);
  101. }
  102. }
  103. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not find a package that matches this request (does user maintain the package?)',)), 404);
  104. }
  105. /**
  106. * @Route("/downloads/{name}", name="track_download", requirements={"name"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"}, defaults={"_format" = "json"})
  107. * @Method({"POST"})
  108. */
  109. public function trackDownloadAction(Request $request, $name)
  110. {
  111. $result = $this->getDoctrine()->getConnection()->fetchAssoc(
  112. 'SELECT p.id, v.id vid
  113. FROM package p
  114. LEFT JOIN package_version v ON p.id = v.package_id
  115. WHERE p.name = ?
  116. AND v.normalizedVersion = ?
  117. LIMIT 1',
  118. array($name, $request->request->get('version_normalized'))
  119. );
  120. if (!$result) {
  121. return new Response('{"status": "error", "message": "Package not found"}', 200);
  122. }
  123. $redis = $this->get('snc_redis.default');
  124. $id = $result['id'];
  125. $version = $result['vid'];
  126. $throttleKey = 'dl:'.$id.':'.$request->getClientIp().':'.date('Ymd');
  127. $requests = $redis->incr($throttleKey);
  128. if (1 === $requests) {
  129. $redis->expire($throttleKey, 86400);
  130. }
  131. if ($requests <= 10) {
  132. $redis->incr('downloads');
  133. $redis->incr('dl:'.$id);
  134. $redis->incr('dl:'.$id.':'.date('Ym'));
  135. $redis->incr('dl:'.$id.':'.date('Ymd'));
  136. $redis->incr('dl:'.$id.'-'.$version);
  137. $redis->incr('dl:'.$id.'-'.$version.':'.date('Ym'));
  138. $redis->incr('dl:'.$id.'-'.$version.':'.date('Ymd'));
  139. }
  140. return new Response('{"status": "success"}', 201);
  141. }
  142. }