Skip to main content
  • Home
  • Development
  • Documentation
  • Donate
  • Operational login
  • Browse the archive

swh logo
SoftwareHeritage
Software
Heritage
Archive
Features
  • Search

  • Downloads

  • Save code now

  • Add forge now

  • Help

https://github.com/Ramy-Badr-Ahmed/swh-client
24 July 2024, 17:59:46 UTC
  • Code
  • Branches (3)
  • Releases (0)
  • Visits
Revision 453153760e2761537d3df9a6930be7cb0883071a authored by Moritz Schubotz on 24 July 2024, 16:51:29 UTC, committed by GitHub on 24 July 2024, 16:51:29 UTC
Fix typo in SWH_TOKEN_PROD
1 parent 8d1239c
  • Files
  • Changes
    • Branches
    • Releases
    • HEAD
    • refs/heads/main
    • refs/tags/v1.0-beta
    • refs/tags/v1.5
    • 453153760e2761537d3df9a6930be7cb0883071a
    No releases to show
  • 1c4ca38
  • /
  • Module
  • /
  • HTTPConnector
  • /
  • SyncHTTP.php
Raw File Download
Take a new snapshot of a software origin

If the archived software origin currently browsed is not synchronized with its upstream version (for instance when new commits have been issued), you can explicitly request Software Heritage to take a new snapshot of it.

Use the form below to proceed. Once a request has been submitted and accepted, it will be processed as soon as possible. You can then check its processing state by visiting this dedicated page.
swh spinner

Processing "take a new snapshot" request ...

To reference or cite the objects present in the Software Heritage archive, permalinks based on SoftWare Hash IDentifiers (SWHIDs) must be used.
Select below a type of object currently browsed in order to display its associated SWHID and permalink.

  • revision
  • directory
  • content
  • snapshot
origin badgerevision badge
swh:1:rev:453153760e2761537d3df9a6930be7cb0883071a
origin badgedirectory badge
swh:1:dir:c632bcaf28d6f51ddf7fe080f1e7759478063892
origin badgecontent badge
swh:1:cnt:24b08d06ba27fe1ef511eb0ade3bc5089f3bf1f0
origin badgesnapshot badge
swh:1:snp:6e93bd2e1f019500326fed8dde08c617dffb20d7

This interface enables to generate software citations, provided that the root directory of browsed objects contains a citation.cff or codemeta.json file.
Select below a type of object currently browsed in order to generate citations for them.

  • revision
  • directory
  • content
  • snapshot
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Tip revision: 453153760e2761537d3df9a6930be7cb0883071a authored by Moritz Schubotz on 24 July 2024, 16:51:29 UTC
Fix typo in SWH_TOKEN_PROD
Tip revision: 4531537
SyncHTTP.php
<?php

/**
 * @Author: Ramy-Badr-Ahmed
 * @Desc: SWH API Client
 * @Repo: https://github.com/Ramy-Badr-Ahmed/swh-client
 */

namespace Module\HTTPConnector;

use Module\Globals\HTTP;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException as GuzzleRequestException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Throwable;

class SyncHTTP extends HTTPClient
{

    public function __construct()
    {
        parent::__construct();

        $this->HTTPRequest = $this->HTTPRequest->withOptions([
            'synchronous' => true
            ]);
    }

    /**
     * @throws RequestException
     */
    public static function call(string $method, string $on, Collection $append2Url, ...$options): Response|iterable|Throwable
    {
        $newHTTP = new self();
        return $newHTTP->invokeEndpoint($method, $on, $append2Url, ...$options);
    }

    /**
     * @param string $method
     * @param string $endpointName
     * @param Collection $append2Url
     * @param ...$options
     * @return Response|iterable|Throwable
     * @throws RequestException
     */
    public function invokeEndpoint(string $method, string $endpointName, Collection $append2Url, ...$options): Response|iterable|Throwable
    {
        $method = Str::lower($method);

        try{
            self::addLogs("Logging started for '".$endpointName."' Endpoint");

            parent::prepareForInvoke($method, $endpointName,$append2Url);

            $uri = is_null($append2Url)
                ? $endpointName
                : Str::replaceArray('~', $append2Url->toArray(), self::$apiURL . self::API_ENDPOINTS[$endpointName]['route']);

            self::addLogs("Invoking '$method' on --> ". $uri);

            $response = $this->HTTPRequest->withOptions(['delay' => $options["delay"] ?? 0, 'debug' => $options["debug"] ?? false])->$method($uri);

            return match (true){
                $response->redirect() => new Exception('Exceeded redirects preset.', '7'),
                $response->successful() && $response->status() === 200 => $response
            };

        }catch(RequestException $e){

            return $this->handleRequestException($e);
        }
        catch(GuzzleRequestException | ConnectionException | ValidationException $e){

            $this->addErrors((match (substr(get_class($e), strrpos(get_class($e), "\\" ) )  ){
                    "\GuzzleRequestException" => "GuzzleHTTP Request Exception occurred --> ",
                    "\ConnectionException" => "Connection Error --> ",
                    "\ValidationException" => "Validation Exception. PrepareForInvoke() Error --> "
                })
                .$e->getCode().": ".$e->getMessage()
            );
            return $e;
        }
        catch(Exception $e){
            $this->addErrors(match(true) {
                $e->getCode() === 980   => "PrepareForInvoke() Error --> " . $e->getMessage(),
                in_array($e->getCode(), self::$serverErrorCodes) => "Server Error --> " . $e->getMessage().": ".$e->getCode(),
                default => "Some other Error occurred: --> " . $e->getMessage().": ".$e->getCode(),
            });
            return $e;
        }
    }

    /**
     * @throws RequestException
     */
    private function handleRequestException(RequestException $e): iterable
    {
        $ErrorResponse = $e->response->json();

        $ErrorMessage = "Non-Successful HTTP Status Code: ".$e->response->status()." --> Reason: ";

        $this->addErrors($ErrorMessage . match (true) {
                $e->response->status() === 403 => "Forbidden Status code. No granted access or invalid token",
                default => $ErrorResponse['reason'] ?? $ErrorResponse
            });

        $contentPattern = substr(self::API_ENDPOINTS['content']['route'], 0, strpos(self::API_ENDPOINTS['content']['route'], ":") + 1 );
        $multipleContentEndpoint = preg_match("#".$contentPattern."([a-fA-F0-9]{40}|[a-fA-F0-9]{64})/[a-z]+#i", $e->response->effectiveUri()->getPath());

        $e->response->throwIf( !$multipleContentEndpoint );

        return $e->response->json();
    }

    /**
     * @param string $method
     * @param string $uri
     * @param ...$options
     * @return Response
     * @throws ClientException|ServerException
     */
    public static function request(string $method, string $uri, ...$options): Response
    {
        $method = Str::lower($method);

        self::addLogs("Invoking '$method' on --> ". $uri);

        return HTTP::withOptions(
            [
                'delay' => $options["delay"] ?? 0,
                'debug' => $options["debug"] ?? false,
                'decode_content' => 'gzip',
                'version' => '1.1',
                'http_errors' => true,
                'verify' => true,
                'force_ip_resolve' => 'v4',
                'allow_redirects' => ['max' => 2, 'protocols' => ['https'], 'track_redirects' => true],
            ])
            ->timeout($options["timeout"] ?? 3)
            ->connectTimeout($options["connectTimeout"] ?? 3)
            ->retry($options["retry"] ?? 3, $options["sleepMS"] ?? 500)
            ->$method($uri);
    }

    /**
     * @param string $method
     * @param string $URI
     * @return bool|Throwable
     */
    public function isHttpMethodAllowed(string $method, string $URI): bool|Throwable
    {
        try{
            self::addLogs("Checking HTTP Method: " . $method . " on --> " . $URI);

            $response = $this->HTTPRequest->head($URI);

            $allowHeader = $response->header('Allow');

            if (!Str::contains($allowHeader, Str::upper($method))) {
                throw new Exception("HTTP method '$method' is not allowed on this endpoint", 405);
            }

            self::addLogs("Method '$method' is allowed on this route");
            return true;

        }catch(RequestException $e){
            $this->addErrors("HEAD Test didn't pass on this given route: ".$e->response->status());
            return $e;
        }catch(Exception $e){
            $this->addErrors($e->getCode() . " : " .$e->getMessage());
            return $e;
        }
    }

}





The diff you're trying to view is too large. Only the first 1000 changed files have been loaded.
Showing with 0 additions and 0 deletions (0 / 0 diffs computed)
swh spinner

Computing file changes ...

back to top

Software Heritage — Copyright (C) 2015–2025, The Software Heritage developers. License: GNU AGPLv3+.
The source code of Software Heritage itself is available on our development forge.
The source code files archived by Software Heritage are available under their own copyright and licenses.
Terms of use: Archive access, API— Content policy— Contact— JavaScript license information— Web API